3

我对 Haskell 比较陌生。

我正在尝试创建一个行为类似于列表函数的函数 。它应该使用给定的 type 函数组合两个输入树。zipWithMult :: (a -> b -> c) -> MultTree a -> MultTree b -> MultTree czipWitha -> b -> c

MultTree表示其节点可能有任意多个子节点的非空树:

data MultTree a = MultNode a [MultTree a] deriving Show

例如,当我有以下两棵树时:

t1 :: MultTree Integer
t1 = MultNode 8 [MultNode 3 [MultNode (-56) [], MultNode 4 [], MultNode 987 []], MultNode 4 [MultNode 6 []]]

t2 :: MultTree Integer
t2 = MultNode (-2) [MultNode 5 [MultNode 16 [], MultNode 7 []], MultNode (-9) [MultNode 1 [], MultNode 5 []]]

该功能的应用zipWithMult (+) t1 t2应导致:

MultNode 6 [MultNode 8 [MultNode (-40) [], MultNode 11 []], MultNode (-5) [MultNode 7 []]] 

在另一棵树中没有对应节点的节点应该被简单地删除。

到目前为止我所拥有的:

zipWithMult :: (a -> b -> c) -> MultTree a -> MultTree b -> MultTree c
zipWithMult f (MultNode x []) (MultNode y ys) = MultNode (f x y) []
zipWithMult f (MultNode x xs) (MultNode y []) = MultNode (f x y) []
zipWithMult f (MultNode x xs) (MultNode y ys) = MultNode (f x y) (zipWithMult f xs ys)

我不明白为什么我的第三次表达会出现这个错误zipWithMult

Couldn't match expected type `MultTree b'
              with actual type `[MultTree b]'
* In the third argument of `zipWithMult', namely `ys'
  In the second argument of `MultNode', namely
    `(zipWithMult f xs ys)'
  In the expression: MultNode (f x y) (zipWithMult f xs ys)

我觉得我在 Haskell 的语法上犯了一个错误,但我不确定。

4

1 回答 1

3

zipWithMult返回一个简单的MultTree,所以MultNode (f x y) (zipWithMult f xs ys)我们有一个问题。

您可以zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]处理两个列表(第一个和第二个参数的项目),并将其作为MultTrees 的列表返回:

zipWithMult :: (a -> b -> c) -> MultTree a -> MultTree b -> MultTree c
zipWithMult f (MultNode x xs) (MultNode y ys)
    = MultNode (f x y) (zipWith (zipWithMult f) xs ys)

对于给定的样本数据,我们得到:

Prelude> zipWithMult (+) t1 t2
MultNode 6 [MultNode 8 [MultNode (-40) [],MultNode 11 []],MultNode (-5) [MultNode 7 []]]
于 2021-05-08T10:43:27.757 回答