Haskell - alternating elements from two lists

前端 未结 5 646
小鲜肉
小鲜肉 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:27

    Your blend function seems to be a limited version of flatZip. The flatZip function is similar but works for any number of lists of varying lengths. Using flatZip to implement blend will cause blend to also support varying lengths by default. Therefore, using a flatZip based approach may not be the way to go in situations where trimming the input lists to equal length is part of the desired behaviour.

    The name flatZip refers to "a zipish way of flattening". Note the -ish part though. We can implement the function by composing concat with transpose. We can add blend on top of flatZip as syntactic sugar to verify that our implementation matches the desired behaviour.

    import Data.List
    
    flatZip = concat . transpose
    flatZip([[1,2],[3],[4,5,6]]) --[1,3,4,2,5,6]
    
    blend xs ys = flatZip [xs, ys]
    blend [1,2,3] [4,5,6] --[1,4,2,5,3,6]
    

提交回复
热议问题