Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 277
Ed George Avatar asked Mar 13 '12 21:03

Ed George


People also ask

How do you concatenate lists in Haskell?

To make a list [1,2,3] you just build it up with 1 : 2 : 3 : [] . The first element of : is the item to add on the front of the list, and the second element is either a list (also built up with : or the empty list signified by [] ). The ++ operator is list concatenation. It takes two lists and appends them together.

What does the concat function do in Haskell?

What does concat do in Haskell? concat flattens a list of lists into just a list of elements.

What is the result if a string data type is concatenated with a list function?

The CONCATENATE function will give the result as a text string. The function converts numbers to text when they are joined.


2 Answers

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]]
like image 101
Cat Plus Plus Avatar answered Nov 02 '22 23:11

Cat Plus Plus


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]]
like image 26
Landei Avatar answered Nov 03 '22 00:11

Landei