英文:
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 -> List a -> List (a, a)
or more generic:
listZip :: List a -> List b -> List (a, b)
Then you implement this with:
<pre><code>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></pre>
where I leave the <code>…</code> part as an exercise.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论