如何访问自定义列表数据类型的元素?

huangapple go评论45阅读模式
英文:

How to access elements of a custom List data type?

问题

我创建了一个自定义的List类型,现在我正在尝试为它实现zip函数。但是我无法弄清楚,它总是在最后一行抛出错误。

data List a = Empty | Cons a (List a) deriving (Eq, Ord, Show, Read)

listZip :: List a -> List a -> List a
listZip _ Empty = Empty
listZip Empty _ = Empty
listZip (Cons x1 x2) (Cons y1 y2) = Cons (Cons x1 y1) (listZip x2 y2)
英文:

I created a custom List type and I'm trying to implement the zip function for it. But I cant figure it out, it always throw an error on the last line.

data List a = Empty | Cons a (List a) deriving (Eq, Ord, Show, Read)

listZip :: List a -> List a -> List a
listZip _ Empty = Empty
listZip Empty _ = Empty
listZip (Cons x1 (x2)) (Cons y1 (y2)) = Cons (Cons x1 y1) (listZip x2 y2)

答案1

得分: 5

返回类型看起来不正确,你可能想要返回一个2元组的列表,所以:

listZip :: List a -> List a -> List (a, a)

或者更通用的方式:

listZip :: List a -> List b -> List (a, b)

然后你可以用以下方式实现:

listZip :: List a -> List b -> List (a, b)
listZip _ Empty = Empty
listZip Empty _ = Empty
listZip (Cons x1 x2) (Cons y1 y2) = Cons ... (listZip x2 y2)

其中,我将 <code>...</code> 部分留给你作为练习。

英文:

The return type looks wrong, you probably want to return a list of 2-tuples, so:

listZip :: List a -&gt; List a -&gt; List (a, a)

or more generic:

listZip :: List a -&gt; List b -&gt; List (a, b)

Then you implement this with:

<pre><code>listZip :: List a -&gt; List b -&gt; List (a, b)
listZip _ Empty = Empty
listZip Empty _ = Empty
listZip (Cons x1 (x2)) (Cons y1 (y2)) = Cons &hellip; (listZip x2 y2)</code></pre>

where I leave the <code>&hellip;</code> part as an exercise.

huangapple
  • 本文由 发表于 2023年2月6日 21:00:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75361639.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定