我正在尝试做一个练习,给出二叉树从叶子到根的每条路径的列表
这是我的代码:
data Tree = Leaf Int | Node (Tree) Int (Tree)
go (Leaf a) = (a : []) : []
go (Node l n r) = insev((go l):(go r)) n
insev :: [[a]] -> a -> [[a]]
insev [[]] x = []
insev (h:t) x = (insb h x) : (insev t x)
insb [] num = num : []
insb (h:t) num = h:(insb t num)
它应该是正确的,从逻辑的角度来看,但我是新的haskell,我不知道为什么我得到这个错误
Main.hs:21:19: error:
• Couldn't match type ‘[Int]’ with ‘Int’
Expected: [[Int]]
Actual: [[[Int]]]
• In the expression: insev ((go l) : (go r)) n
In an equation for ‘go’:
go (Node l n r) = insev ((go l) : (go r)) n
|
21 | go (Node l n r) = insev ((go l):(go r)) n
| ^^^^^^^^^^^^^^^^^^^^^^^
Main.hs:21:34: error:
• Couldn't match type ‘Int’ with ‘[Int]’
Expected: [[[Int]]]
Actual: [[Int]]
• In the second argument of ‘(:)’, namely ‘(go r)’
In the first argument of ‘insev’, namely ‘((go l) : (go r))’
In the expression: insev ((go l) : (go r)) n
|
21 | go (Node l n r) = insev ((go l):(go r)) n
| ^^^^
Main.hs:21:41: error:
• Couldn't match expected type ‘[Int]’ with actual type ‘Int’
• In the second argument of ‘insev’, namely ‘n’
In the expression: insev ((go l) : (go r)) n
In an equation for ‘go’:
go (Node l n r) = insev ((go l) : (go r)) n
|
21 | go (Node l n r) = insev ((go l):(go r)) n
甚至不看剩下的代码,这是永远不会*将飞行:
(go l) : (go r)
假定go
在两次调用中返回相同类型的东西,但(:)
的参数必须具有不同的类型:
(:) :: a -> [a] -> [a]
也许你想用(++)
代替,它的参数必须有相同的类型:
(++) :: [a] -> [a] -> [a]
*好的,是的,有可能以一种方式编写go
,使下一个句子的假设无效,即它在两个调用中返回相同的类型。但这是一种非常不寻常的情况,你必须非常有意识地尝试到达。