帮助声明可变数目的参数 [英] Help In Declaring Variable Number Of Arguments
问题描述
高手们,
我必须为可以有多个节点的树定义多态数据类型。每个节点可以有任意数量的子节点和一个vlaue。这种类型将始终至少有一个节点。我是Haskell的新手,所以我问如何声明节点具有可变数量的参数。
这是我现在拥有的。这是一棵树,可以有一个节点或一个节点值为(a)和两个树孩子。我希望他们成为任何数量的树孩子,而不是两个树孩子。 (Analoog as java可变参数数量arg ...)
数据树a =节点a |节点a(Tree a)(Tree a)派生(显示)
感谢您的帮助
编辑
有点问题:::我怎样才能用变量声明这个节点在函数
参数(头/签名)中。我必须实现一个称为
contains的函数,它将检查Node是否包含特定元素。
包含:: Tree a - > b - > Bool
包含(Node val [(tree)])= ......
第二行是否正确?
数据树a =节点a |节点a [(Tree a)]派生(Show)
但是另外还有一个问题,这应该是
数据树a = Leaf a | Branch a [(Tree a)]派生(Show)
或者联合的部分必须有不同的名称,否则你不能使用模式匹配。
Leaf
和分支
是数据构造函数,所以:
分支1 [分支3,分支6 [分支5]]
是树的示例
contains :: Tree a - > a - >布尔
包含(Leaf a)b = a == b
包含(Branch a c)b = a == b ||任何(地图(\ t - >包含tb)c)
或其他
High Guys,
I have to define a polymorphic datatype for a tree that can have multiple nodes. Each node can have any number of children and a vlaue. This type will always have at least one node. I am new in Haskell so am asking how can i declare the node to have variable number of arguments.
This is what i have now. This is a tree that can have a Node or a node with value (a) and two tree children. Instead of two tree children, i want them to be any number of tree children. (Analoog as java variable number of arguments "arg...")
data Tree a = Node a | Node a (Tree a) (Tree a) deriving (Show)
Thanks for your help
EDIT
A little question::: How can i declare this node with variable arguments in a functions
parameter(header/signature). I have to implement a function called
"contains" which will check if a Node contains a specific element.
contains :: Tree a -> b -> Bool
contains (Node val [(tree)]) = ......
Is the second line correct ?
it would be:
data Tree a = Node a | Node a [(Tree a)] deriving (Show)
but in addition there is a second problem that this should be
data Tree a = Leaf a | Branch a [(Tree a)] deriving (Show)
or such as the parts of a union must have different names as otherwise you couldn't use pattern matching
Leaf
and Branch
are data constructors so:
Branch 1 [Leaf 3, Branch 6 [Leaf 5]]
is an example of a Tree
contains :: Tree a -> a -> Boolean
contains (Leaf a) b = a == b
contains (Branch a c) b = a == b || any (map (\t -> contains t b) c)
or such
这篇关于帮助声明可变数目的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!