Jivan
Jivan

Reputation: 23088

Map over IO [Int] in GHCI

I'd like to know how to map over an IO [Int] in GHCI.

λ: :{
λ| th :: IO [Int]
λ| th = pure [1, 2, 3, 4]
λ| :}
λ: th
[1,2,3,4]
λ: :t th
th :: IO [Int]
λ: map (+2) th
    • Couldn't match expected type ‘[b]’ with actual type ‘IO [Int]’
    • In the second argument of ‘map’, namely ‘th’
      In the expression: map (+ 2) th

Desired result:

λ: res = map (+2) th -- <-- some working version of this
λ: res
[3, 4, 5, 6]
λ: :t res
res :: IO [Int]

The solution is probably very obvious but somehow I can't wrap my head around it.

Upvotes: 3

Views: 254

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477328

You can make use of fmap :: Functor f => (a -> b) -> f a -> f b to performing a mapping over the values of a Functor. Since IO is a functor, you can thus use this to post-process the result of an IO action:

Prelude> fmap (map (+2)) th
[3,4,5,6]

You can also use the infix operator (<$>) :: Functor f => (a -> b) -> f a -> f b which is an alias:

Prelude> map (+2) <$> th
[3,4,5,6]

Upvotes: 6

Related Questions