Search code examples
haskellpointfree

Concatenation of lists in Haskell


I want a function that takes two lists of any type and returns one (i.e. f:: [[a]] -> [[a]] -> [[a]]). Basically, too produce the 'concatenation' of the two input lists.

e.g.

> f [[1,2,3], [123]] [[4,5,6], [3,7]]
[[1,2,3,4,5,6], [1,2,3,3,7], [123,4,5,6], [123,3,7]]

I currently have got this far with it:

f _ [] = []
f [] _ = []
f (xs:xss) (ys:yss) = ((xs ++ ys) : [m | m <- f [xs] yss])

But this doesn't take into account xss and is wrong. Any suggestions?


Solution

  • It's a Cartesian product, so you can simply use one list comprehension to do everything.

    Prelude> let xs = [[1,2,3], [123]]
    Prelude> let ys = [[4,5,6], [3,7]]
    Prelude> [x ++ y | x <- xs, y <- ys]
    [[1,2,3,4,5,6],[1,2,3,3,7],[123,4,5,6],[123,3,7]]