我想将任意列表按位置拆分成两个新列表,一个包含所有偶数元素,另一个包含所有奇数元素。
例如:
对于这样的列表:
["a", "b", "c", "d", "e"]
我该如何获得这样的两个列表:
(["a", "c", "e"], ["b", "d"])
单次遍历和少量代码:
evensAndOdds : List a -> (List a, List a)
evensAndOdds =
List.foldr (\item (a, b) -> (item :: b, a)) ([], [])
解决方案1:
evensAndOdds : List a -> (List a, List a)
evensAndOdds items
let
enum = List.indexedMap Tuple.pair items
evens = List.filterMap (\(i, v) -> if modBy 2 i == 0 then Just v else Nothing) enum
odds = List.filterMap (\(i, v) -> if modBy 2 i == 1 then Just v else Nothing) enum
in
(evens, odds)
evensAndOdds : List a -> (List a, List a)
evensAndOdds =
List.indexedMap (\i v -> (modBy 2 i == 0, v))
>> List.partition Tuple.first
>> Tuple.mapFirst (List.map Tuple.second)
>> Tuple.mapSecond (List.map Tuple.second)
fold
更易读。evensAndOdds : List a -> ( List a, List a )
evensAndOdds input =
case input of
[] ->
( [], [] )
[ even ] ->
( [ even ], [] )
[ even, odd ] :: tail ->
let
( tailEvens, tailOdds ) =
evensAndOdds tail
in
( even :: tailEvens, odd :: tailOdds )
foldl
,它会这样做,但是这里使用的是foldr
。 - glennsl