在GHCI中的IO [Int]上进行映射

我想知道如何在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

解决方案可能非常明显,但不知何故我无法解决问题。

yuhailin405 回答:在GHCI中的IO [Int]上进行映射

您可以使用fmap :: Functor f => (a -> b) -> f a -> f bFunctor的值执行映射。由于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]
本文链接:https://www.f2er.com/1296106.html

大家都在问