您好我想定义plusTree.
对此的定义.

data Tree = Null | Node Int Tree Tree deriving Show
plusTree :: Tree -> Tree -> Tree
plusTree Null ys = Null
plusTree xs Null = Null
plusTree (Node x xs) (Node y ys) = Node (x+y) (plusTree xs ys)
Run Code Online (Sandbox Code Playgroud)
我创建了上面的代码.
构造函数"Node"应该有3个参数,但是已经给出了2个参数
在模式中:节点x xs
在`plusTree'的等式中:plusTree(Node x xs)(Node y ys)= Node(x + y)(交互式:IHaskell544.plusTree xs ys)
我也遇到了上述错误.所以我尝试了各种方法.我最后虽然在第四个参数中添加一些内容时它会起作用.
plusTree :: Tree -> Tree -> Tree
plusTree Null ys = Null
plusTree xs Null = Null
plusTree (Node x xs) (Node y ys)(Node z zs) = Node (x+y+z) (plusTree xs ys zs)
Run Code Online (Sandbox Code Playgroud)
现在我又出了一个错误.我也尝试了几种方法.但无法修复它.
'plusTree'的方程有不同数量的参数'
:2:1-35
:4:1-79
有人可以提供建议或解决方案来帮助我吗?现在我被阻挡在墙上.
编译器并没有抱怨的参数的数量plusTree的功能.它抱怨你的Node构造函数应该有三个参数.确实:
data Tree = Null | Node Int Tree Tree deriving ShowRun Code Online (Sandbox Code Playgroud)
因此,您在此定义一个具有三个参数Node的数据构造函数:an Int和two Trees.但是在你的函数中,你只写了两个:
plusTree (Node x xs) (Node y ys) = Node (x+y) (plusTree xs ys) Run Code Online (Sandbox Code Playgroud)
因此,这不是一个正确的Node例子.
我假设这是某种二叉树,其中第二个参数是左子树,第三个参数是右子树.在这种情况下,我们需要执行双递归:
plusTree :: Tree -> Tree -> Tree
plusTree Null ys = Null
plusTree xs Null = Null
plusTree (Node x lx rx) (Node y ly ry) = Node (x+y) (plusTree lx ly) (plusTree rx ry)Run Code Online (Sandbox Code Playgroud)
第一个子句定义变量xs,ys而不使用.在这种情况下,通常使用下划线,这样如果我们打开所有警告,编译器将不会抱怨未使用的变量:
plusTree :: Tree -> Tree -> Tree
plusTree Null _ = Null
plusTree _ Null = Null
plusTree (Node x lx rx) (Node y ly ry) = Node (x+y) (plusTree lx ly) (plusTree rx ry)Run Code Online (Sandbox Code Playgroud)