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 nod开发者_高级运维e. 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
精彩评论