haskell - 无法将预期类型 'MultTree b' 与 '[MultTree b]' 匹配

标签 haskell syntax tree zipwith

我对 Haskell 还比较陌生。

我正在尝试创建一个函数 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 中的语法上犯了一个错误,但我不确定。

最佳答案

zipWithMult 返回一个简单的 MultTree,因此对于 MultNode (f x y) (zipWithMult f xs ys) 我们遇到了问题。

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

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

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

Prelude> zipWithMult (+) t1 t2
MultNode 6 [MultNode 8 [MultNode (-40) [],MultNode 11 []],MultNode (-5) [MultNode 7 []]]

关于haskell - 无法将预期类型 'MultTree b' 与 '[MultTree b]' 匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67446581/

相关文章:

npm - 使用Inquirer时 'List'和 'Rawlist'有什么区别

syntax - 是否可以在 idris 的函数定义中使用守卫?

algorithm - 从右到左遍历一棵树

list - 获取 Haskell 列表中下一个最小元素的索引

haskell - 如何减少 Haskell 中必须传递的参数数量?

haskell - 我可以用什么代替 `case of` 来减少代码?

javascript - parent (或 parent 夫妇)的家谱

haskell - Numeric.AD - 类型变量脱离其作用域

javascript - 用于 Javascript 对象的位移运算符

algorithm - 如何从给定的列表中有效地构建 B+ 树?