【问题标题】:Map over IO [Int] in GHCI在 GHCI 中映射 IO [Int]
【发布时间】:2020-11-01 17:36:59
【问题描述】:

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

解决方案可能很明显,但不知何故我无法理解它。

【问题讨论】:

    标签: haskell ghci io-monad


    【解决方案1】:

    您可以使用fmap :: Functor f =&gt; (a -&gt; b) -&gt; f a -&gt; f bFunctor 的值执行映射。由于IO 是一个仿函数,因此您可以使用它后处理IO 操作的结果:

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

    您也可以使用中缀运算符(&lt;$&gt;) :: Functor f =&gt; (a -&gt; b) -&gt; f a -&gt; f b,这是一个别名:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-22
      • 2015-08-27
      • 2012-04-06
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 2021-08-18
      相关资源
      最近更新 更多