在Haskell获取玫瑰树的根 [英] Get the root of a Rose tree in Haskell
问题描述
编写函数root :: Rose a - > a和children :: Rose a - > [Rose a]
,它们分别返回存储在玫瑰树根部的值,即玫瑰树的
根部的子元素。
他们给我下面的基本代码开始:
data Rose a = a:[Rose a]
derived(Eq,Show)
吨知道什么(:>)的意思。我尝试通过输入ghci来理解它:
输入::t(:>)
输出:a - > [玫瑰a] - > Rose a
所以我认为这意味着你有一个 a
value,它将用于从列表中查找 Rose a
并返回 Rose a
,但我仍然困惑下一步该做什么。
如果我看一下 root的签名:Rose a - >一个
,函数看起来像这样:
root(Rose a)= a
children的功能:: Rose a - > [Rose a]
:
children(Rose a)=(Rose a):[]
这是不正确的,我不知道如何使它正确。
声明
数据Rose a = a:> [玫瑰a]
基本上相当于
< pre $ 数据Rose a = Node a [Rose a]
换句话说, Node
是一个包含一个数据和一个子节点列表的数据结构。但是在上面的定义中,不是称它为 Node
,而是叫做:>
。这只是一个虚构的名字; Haskell允许您创建像这样的用户定义的操作符。
如果使用名称 Node
,您可以编写
$ b $
root(Node datum children)= datum
或者,更简单地说,
root(Node a rs)= a
由于给定的名称实际上是:>
,你必须把它写成
root(a:> rs)= a
特别是,您似乎试图使用 Rose
,但那是类型构造函数,而不是值构造函数。同样,你似乎试图使用:
运算符,但这是列表而不是玫瑰树。
<希望能为你清除一些东西。
Recently I started to learn about Haskell, and am struggling with the following exercise:
Write functions root :: Rose a -> a and children :: Rose a -> [Rose a] that return the value stored at the root of a rose tree, respectively the children of the root of a rose tree.
They gave me the following basic code to start:
data Rose a = a :> [Rose a] deriving (Eq, Show)
I don't know what (:>) means. I tried to understand it by typing in the ghci
Input: :t (:>)
Output: a -> [Rose a] -> Rose a
So I think it means that you have an a
value, which will be used to lookup Rose a
out of a list and returns Rose a
, but I'm still confused what to do next.
If I look at the signature of root :: Rose a -> a
, the function would look like this:
root (Rose a) = a
And the function of children :: Rose a -> [Rose a]
:
children (Rose a) = (Rose a):[]
This is not correct, and I don't how to make it correct.
The declaration
data Rose a = a :> [Rose a]
is basically equivalent to
data Rose a = Node a [Rose a]
In other words, Node
is a data structure containing a datum and a list of child nodes. But in the definition above, rather than calling it Node
, it's called :>
. It's just a made-up name; Haskell allows you to create user-defined operators like this.
If the name Node
was used, you could write
root (Node datum children) = datum
Or, more briefly,
root (Node a rs) = a
Since the name given is actually :>
, you'd have to write it as
root (a :> rs) = a
In particular, you seem to be trying to use Rose
, but that's the type constructor, not the value constructor. Similarly, you seem to be trying to use the ":
" operator, but that's for lists, not rose trees.
Hopefully that clears up some things for you.
这篇关于在Haskell获取玫瑰树的根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!