简体   繁体   English

Haskell-循环列表的第二个元素

[英]Haskell- looping every second element of list

I want to be able to loop every second element of a given list. 我希望能够循环给定列表的每个第二个元素。 I can do this recursively as so: 我可以这样递归地执行此操作:

check validate (x:xs) = check (validate x) (tail xs)

But the problem is that I need a function that accepts a list as parameter, then returns a list consisting of only every second element in the list, starting with (and including) the first element of the list, and I do not think this is possible recursively. 但是问题是我需要一个函数,该函数接受一个列表作为参数,然后返回一个列表,该列表仅由列表中的每个第二个元素组成,并从列表的第一个元素开始(包括),而我不认为这是可能递归。

Can someone show me how to this using list comprehension? 有人可以告诉我如何使用列表理解吗? This would probably be the best approach. 这可能是最好的方法。

second (x:y:xs) = y : second xs;
second _ = []

List comprehension may not be useful. 列表理解可能没有用。

You can also try mutual recursion 您也可以尝试相互递归

first [] = []
first (x:xs) = x:second xs

second [] = []
second (x:xs) = first xs

such as

> first [1..10]
[1,3,5,7,9]

> second [1..10]
[2,4,6,8,10]

One of the Haskellish approaches would be something with map , filter , and zip . Haskellish方法之一是使用mapfilterzip

second xs = map fst $ filter (odd . snd) $ zip xs [1..]

If you really wanted to use list comprehension, you could use the parallel list comprehension extension. 如果您真的想使用列表理解,可以使用并行列表理解扩展。

{-# LANGUAGE ParallelListComp #-}
second xs = [ x | (x, n) <- [ (x, n) | x <- xs | n <- [1..] ], odd n ]

I think that the former is concise, though. 我认为前者是简洁的。

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

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