简体   繁体   English

如何使这个列表解构在 haskell 中运行良好?

[英]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?我能得到一些帮助吗?

  1. Specify the function that produces an ordered pair from a list.指定从列表生成有序对的函数。 The first element of the pair is the first element of the list and the second element of the pair is part of the tail of the list be.该对的第一个元素是列表的第一个元素,该对的第二个元素是列表尾部的一部分。 We can assume that the list is not empty.我们可以假设列表不为空。
headTail :: [a] -> (a, [a])
headTail (l: ls) = (headTail l, [ls])
  1. Give the function that gets two lists and produces an ordered pair, the first element of which is the first element of the first list, the second element of which is the second list first element!给出获取两个列表并生成一个有序对的函数,其中的第一个元素是第一个列表的第一个元素,其中的第二个元素是第二个列表的第一个元素! We can assume that none of the lists are empty.我们可以假设没有一个列表是空的。
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 _ ).因此,我们将它们模式匹配为xy并且根本不捕获其余部分(由_表示)。 And return them as a tuple.并将它们作为元组返回。

doubleHead :: [a] -> [b] -> (a, b)
doubleHead (x:_) (y:_) = (x, y)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM