List Concatenation in Haskell

I need a function that takes two lists of any type and returns one (i.e. f:: [[a]] -> [[a]] -> [[a]]). Basically, also create a "concatenation" of the two input lists.

eg.

> 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]]

Currently, I got this far:

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

But this does not take into account xssand is incorrect. Any suggestions?

+5
source share
5 answers

This is a Cartesian product, so you can simply use one list comprehension to do it all.

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]]
+9
source
import Control.Applicative

(++) <$> [[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]]
+3
source
f l1 l2 = [x ++ y | x <- l1, y <- l2]
+3
source

In Alternative:

import Control.Applicative

f :: (Applicative f, Alternative g) => f (g a) -> f (g a) -> f (g a)
f = liftA2 (<|>)
+2
source
f a b = map concat . sequence $ [a,b]

Increases the number of combo boxes.

+1
source

All Articles