帮助声明可变数量的参数

发布于 2024-10-05 23:01:54 字数 556 浏览 4 评论 0原文

高人,

我必须为可以有多个节点的树定义一个多态数据类型。每个节点可以有任意数量的子节点和一个值。这种类型总是至少有一个节点。我是 Haskell 的新手,所以我问如何声明节点具有可变数量的参数。

这就是我现在所拥有的。这是一棵树,可以有一个节点或一个值为 (a) 的节点和两个树子节点。我希望它们是任意数量的树孩子,而不是两个树孩子。 (类似于java可变参数数量“arg...”)

data Tree a = Node a | Node a (Tree a) (Tree a) deriving (Show)

感谢您的帮助

编辑

一个小问题:::我如何在函数中使用可变参数声明这个节点 参数(标头/签名)。我必须实现一个名为
的函数 “contains”将检查节点是否包含特定元素。

contains :: Tree a -> b -> Bool
contains (Node val [(tree)]) =   ......

第二行正确吗?

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 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

李不 2024-10-12 23:01:54

它将是:

data Tree a = Node a | Node a [(Tree a)] deriving (Show)

但此外还有第二个问题,这应该是

data Tree a = Leaf a | Branch a [(Tree a)] deriving (Show)

或者例如联合的各个部分必须具有不同的名称,否则您无法使用模式匹配

LeafBranch 是数据构造函数,因此:

Branch 1 [Leaf 3, Branch 6 [Leaf 5]]

的示例


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)

Tree

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文