[英]How can I make this list deconstruction work well in haskell?
I have got 2 exercise, but I do not understand how can I make them work.我有 2 个练习,但我不明白如何让它们工作。 I tried to figure it out but I don't understand.
我试图弄清楚,但我不明白。 Can I get some help?
我能得到一些帮助吗?
headTail :: [a] -> (a, [a])
headTail (l: ls) = (headTail l, [ls])
doubleHead :: [a] -> [b] -> (a, b)
doubleHead (l:ls) =
I would use pattern matching in both cases.我会在这两种情况下使用模式匹配。
(l:ls)
assigns the first element of the list to l
and the rest to ls
. (l:ls)
将列表的第一个元素分配给l
,将其余元素分配给ls
。 You can return them as a tuple as instructed.您可以按照说明将它们作为元组返回。
headTail :: [a] -> (a, [a])
headTail (l:ls) = (l, ls)
Here we only care about the first elements of both lists.这里我们只关心两个列表的第一个元素。 So, we pattern match them into
x
, and y
and don't capture the rest at all (indicated by _
).因此,我们将它们模式匹配为
x
和y
并且根本不捕获其余部分(由_
表示)。 And return them as a tuple.并将它们作为元组返回。
doubleHead :: [a] -> [b] -> (a, b)
doubleHead (x:_) (y:_) = (x, y)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.