Interleave List of Lists in Haskell

后端 未结 4 1982
借酒劲吻你
借酒劲吻你 2020-12-16 23:57

I was wondering how could I write a function in Haskell that interleaves a list of lists into a single lists, for example, if I had a function called

interleav

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-17 00:09

    we could do what you want

    testList = [[1,2,3],[4,5,6],[7,8]]
    
    interleave l = foldr' (concat [map (\x -> f x idx) l | idx <- [0..]])  
        where
            f x n = if (length(x)<=n) then Nothing else Just (x !! n)
            foldr' (x:xs) = case x of 
                             Nothing -> []
                             Just a  -> (:) a (foldr' xs)   
    

    As required interleave [[1,2,3] [4,5,6] [7,8]] => [1, 4, 7, 2, 5, 8, 3, 6]

提交回复
热议问题