Haskell - alternating elements from two lists

前端 未结 5 650
小鲜肉
小鲜肉 2021-02-07 12:51

I\'m trying to write a haskell function that takes in two lists of integers and generates a list with elements that have been taken alternatingly from the two lists.

I

5条回答
  •  盖世英雄少女心
    2021-02-07 13:40

    A solution without using concat or explicit recursion:

    blend l = foldr($)[] . zipWith(.) (map(:)l) . map(:)
    

    We can make also make this point-free

    blend' = (foldr($)[].) . (.map(:)) . zipWith(.) . map(:)
    


    How it works: first decorate both lists with cons operators

    \[1,2,3] [4,5,6] -> [1:, 2:, 3:] [4:, 5:, 6:]
    

    then we zip this together with function composition

    -> [(1:).(4:), (2:).(5:), (3:).(6:)]
    

    and finally fold the application of all these compositions from the right to the empty list

    -> (1:).(4:) $ (2:).(5:) $ (3:).(6:) $ [] = 1:4:2:5:3:6:[] = [1,4,2,5,3,6]
    

提交回复
热议问题