我对 Haskell 比较陌生。
我正在尝试创建一个行为类似于列表函数的函数 。它应该使用给定的 type 函数组合两个输入树。zipWithMult :: (a -> b -> c) -> MultTree a -> MultTree b -> MultTree c
zipWith
a -> 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 的语法上犯了一个错误,但我不确定。