Jiv*_*van 3 haskell ghci io-monad
我想知道如何IO [Int]在 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
Run Code Online (Sandbox Code Playgroud)
想要的结果:
?: res = map (+2) th -- <-- some working version of this
?: res
[3, 4, 5, 6]
?: :t res
res :: IO [Int]
Run Code Online (Sandbox Code Playgroud)
解决方案可能非常明显,但不知何故我无法理解它。
您可以利用 对fmap :: Functor f => (a -> b) -> f a -> f ba 的值执行映射Functor。由于IO是函子,因此您可以使用它来对操作的结果进行后处理IO:
Prelude> fmap (map (+2)) th
[3,4,5,6]
Run Code Online (Sandbox Code Playgroud)
您还可以使用(<$>) :: Functor f => (a -> b) -> f a -> f b作为别名的中缀运算符:
Prelude> map (+2) <$> th
[3,4,5,6]
Run Code Online (Sandbox Code Playgroud)