繁体   English   中英

haskell中包含列表成员的第二个元素的列表

[英]list containing the second elements of the list members in haskell

我试图解决上一年的一个旧的中期问题,与此同时我遇到了很多麻烦。

使用列表推导,实现以下类型的函数:

collectSecond :: [[Int]] -> [Int]

这样,(collectSecond xs)返回一个包含xs列表成员的第二个元素的列表,但长度小于2的那些列表成员除外。 例如:

collectSecond [[1,2,3], [4], [], [5,6]] ~> [2,6]
collectSecond [[1], [], [2]] ~> []
collectSecond [] ~> []

任何帮助,将不胜感激。

您可以在列表推导中使用模式匹配来找出第二个元素,如下所示:

collectSecond xs = [x2 |  x1:x2:rest <-  xs]

这里x2匹配xs包含的每个列表的第二个元素(如果有)。

Prelude> collectSecond [[1,2,3], [4], [], [5,6]]
[2,6]

并且如果没有第二个元素,则没有元素添加到该子列表的列表中。 例如,请参见上面示例中的[4]和[]。

使用基本递归也很容易实现:

collectSecond ((x0:x1:_):ys) = x1:(collectSecond ys)
collectSecond (_:ys)         = collectSecond ys
collectSecond []             = []

(在这里,我们分别处理每个元素,如果有一个元素,则将其seconds元素添加到我们正在创建的列表中,如果没有第二个元素,则将其跳过)

您也可以使用concatMap

collectSecond xs = concatMap seconds xs
    where seconds (x0:x1:_) = [x1]
          seconds _         = []

暂无
暂无

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

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