繁体   English   中英

有没有一种方法可以解决Haskell中不同数量的参数?

[英]Is there a way to solve different numbers of arguments in Haskell?

您好,我想定义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) 

然后创建上面的代码。

构造函数“节点”应具有3个参数,但已赋予2个参数

在模式中:Node x xs

在针对plusTree的方程式中:plusTree(Node x xs)(Node y ys)= Node(x + y)(交互式:IHaskell544.plusTree xs ys)

我也遇到了上面的错误。 所以我尝试了各种方法。 当我在第4个参数中添加一些内容时,我终于可以正常工作了。

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)

现在我又遇到了另一个错误。 而且我再次尝试了几种方法。 但无法解决。

“ plusTree的方程具有不同数量的参数”

:2:1-35

:4:1-79

有人可以提供建议或解决方案来帮助我吗? 现在我被堵在墙上了。

编译器抱怨的参数的数量plusTree功能。 它抱怨您的Node构造函数应具有三个参数。 确实:

data Tree = Null | Node Int Tree Tree deriving Show

因此,在这里您将Node定义为具有三个参数的数据构造函数: Int和两个Tree 但是在您的函数中,您只编写了其中两个:

plusTree (Node x xs) (Node y ys) = Node (x+y) (plusTree xs ys) 

因此,这不是正确的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)

第一条定义了您不使用的变量xsys 在这种情况下,通常使用下划线,这样,如果我们打开所有警告,则编译器将不会抱怨未使用的变量:

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)

编译器告诉您在此行中您将节点应用错误:

plusTree (Node x xs) (Node y ys) = Node (x+y) (plusTree xs ys) 

因为节点采用“ Int Tree Tree”,而您尝试将其与“ x xs”匹配

哦,那前2种情况都等于0 + n对吗? 他们不应该是n吗?

更改代码:

    plusTree :: Tree -> Tree -> Tree
    plusTree Null         ys     = ys
    plusTree xs          Null    = xs
    plusTree (Node x lxTree rxTree) (Node y lyTree ryTree)  = 
        Node (x+y) (plusTree lxTree lyTree) (plusTree rxTree lyTree)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM