在 GHCI 中映射 IO [Int]
Map over IO [Int] in GHCI
我想知道如何在 GHCI 中映射 IO [Int]
。
λ: :{
λ| 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
想要的结果:
λ: res = map (+2) th -- <-- some working version of this
λ: res
[3, 4, 5, 6]
λ: :t res
res :: IO [Int]
解决方案可能非常明显,但不知何故我无法理解它。
你可以利用fmap :: Functor f => (a -> b) -> f a -> f b
to performing a mapping over the values of a Functor
。由于 IO
是一个仿函数,因此您可以将其用于 post-process IO
操作的结果:
Prelude> fmap (map (+2)) th
[3,4,5,6]
您还可以使用中缀运算符 (<$>) :: Functor f => (a -> b) -> f a -> f b
这是一个别名:
Prelude> map (+2) <$> th
[3,4,5,6]
我想知道如何在 GHCI 中映射 IO [Int]
。
λ: :{
λ| 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
想要的结果:
λ: res = map (+2) th -- <-- some working version of this
λ: res
[3, 4, 5, 6]
λ: :t res
res :: IO [Int]
解决方案可能非常明显,但不知何故我无法理解它。
你可以利用fmap :: Functor f => (a -> b) -> f a -> f b
to performing a mapping over the values of a Functor
。由于 IO
是一个仿函数,因此您可以将其用于 post-process IO
操作的结果:
Prelude> fmap (map (+2)) th
[3,4,5,6]
您还可以使用中缀运算符 (<$>) :: Functor f => (a -> b) -> f a -> f b
这是一个别名:
Prelude> map (+2) <$> th
[3,4,5,6]