data Node = Blue | Green | Red
data Tree = Leaf Node | Node [Tree]
main = do
let a = Blue[Leaf Red]
print 1
它给了我以下错误:
main.hs:5:15: error:
• Couldn't match expected type ‘[Tree] -> t’
with actual type ‘Node’
• The function ‘Blue’ is applied to one argument,
but its type ‘Node’ has none
In the expression: Blue [Leaf Red]
In an equation for ‘a’: a = Blue [Leaf Red]
• Relevant bindings include a :: t (bound at main.hs:5:11)
而且我不明白为什么它说它得到了Node而不是[Tree]
答案 0 :(得分:6)
您可以使用其中一种颜色创建Tree
作为单个叶子,例如Leaf Red
或作为具有其他树列表的节点,例如Node [Leaf Red]
。您的main
函数应如下所示:
main = do
let a = Node [Leaf Red]
print 1
或者:
main = do
let a = Node [Leaf Blue, Leaf Red]
print 1
如果您还想为节点添加颜色,可以将Tree
数据类型重新定义为:
data Tree = Leaf Node | Node Node [Tree]
...
let a = Node Blue [Leaf Red]
阅读此内容可能会造成混淆,因此您应该考虑重命名Node
类型或Node
数据构造函数。