Help In Declaring Variable Number Of Arguments

我的梦境 提交于 2019-12-11 09:27:21

问题


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 ?


回答1:


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



来源:https://stackoverflow.com/questions/4341816/help-in-declaring-variable-number-of-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!