问题描述
我想知道如何在GHCI中映射{place0: 1,place1: 2,place2: 3,place3: 4}
。
IO [Int]
所需结果:
λ: :{
λ| th :: IO [Int]
λ| th = pure [1,2,3,4]
λ| :}
λ: th
[1,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
解决方法
您可以使用fmap :: Functor f => (a -> b) -> f a -> f b
对Functor
的值执行映射。由于IO
是函子,因此您可以使用它来对IO
动作的结果进行后处理:
Prelude> fmap (map (+2)) th
[3,4,5,6]
您还可以使用中缀运算符(<$>) :: Functor f => (a -> b) -> f a -> f b
,它是别名:
Prelude> map (+2) <$> th
[3,6]