David
David

Reputation: 674

How to concatenate list in map function - Haskell?

I have two functions:

fun1 :: Int -> [Int]
fun2 :: [Int] -> [Int]

fun2 accept Int list and apply fun1 to each element of this list with help map. But fun1 return [Int]. So, I have type conflict. How to solve my problem?

Upvotes: 3

Views: 3587

Answers (3)

mb14
mb14

Reputation: 22596

The ability to transform [[a]] to [a] is what make List (among other thing) a Monad. Therefore you can use the do notation :

fun2 xs = do 
     x <- xs
     fun1 x

which can the be rewritten fun2 xs = xs >>= fun1 or even better

fun2 = (>>= fun1)

Upvotes: 4

Will Ness
Will Ness

Reputation: 71070

Another way is with list comprehension. Mapping fun1 over the list xs is

fun2' xs = [ fun1 x | x <- xs ]
     --  =  map fun1 xs
     --  =  do x <- xs                -- for each x in xs:
     --        return (fun1 x)        --    yield (fun1 x)

which indeed would have a different type than what you wanted.

To flatten it one step further we do

fun2  xs = [ y | x <- xs, y <- fun1 x ]
     --  = concatMap fun1 xs
     --  =  do x <- xs                -- for each x in xs:
     --        y <- fun1 x            --    for each y in (fun1 x):
     --        return y               --       yield y

Upvotes: 2

Sibi
Sibi

Reputation: 48644

You likely want a combination of map and concat to achieve it. Assuming fun1 and fun2 are something like this:

fun1 :: Int -> [Int]
fun1 x = [x,x]

fun2 :: [Int] -> [Int]
fun2 = map (+ 1)

solution :: [Int] -> [Int]
solution xs = concat $ map fun1 (fun2 xs)

Or as suggested by @CarstenKonig, you can use concatMap

solution2 :: [Int] -> [Int]
solution2 xs = concatMap fun1 $ fun2 xs

which can be further simplified to:

solution2 :: [Int] -> [Int]
solution2 = concatMap fun1 . fun2

Upvotes: 6

Related Questions