在 ghci 中获取 IO Monad 的结果
Getting Result of IO Monad in ghci
鉴于:
Prelude> let x = return 100 :: IO Int
正在尝试评估 x
returns 其包装值。
Prelude> x
100
但是,我无法通过 show
获取它的值。
Prelude> show x
<interactive>:4:1:
No instance for (Show (IO Int)) arising from a use of ‘show’
In the expression: show x
In an equation for ‘it’: it = show x
当我在 ghci 中输入 x
时发生了什么?
如果您在 GHCi 中输入 IO t
类型的表达式,它会解包并打印结果值。也就是说,如果您输入 ioExp
,GHCi 会执行 val <- ioExp; print val
(而如果您输入非 IO 表达式 exp
,GHCi 会执行 print exp
)。
您不能 show
执行 IO Int
操作。该操作可能需要执行副作用以产生 Int
,例如向用户询问此类数字。相反,show
的类型承诺 return 和 String
,即没有任何副作用的纯字符串。
如果需要,您可以定义自己的 show
有效变体:
showIO :: Show a => IO a -> IO String
showIO = fmap show
请注意上面的结果不是纯字符串,而是包含在 IO
monad 中,它应该是这样。
鉴于:
Prelude> let x = return 100 :: IO Int
正在尝试评估 x
returns 其包装值。
Prelude> x
100
但是,我无法通过 show
获取它的值。
Prelude> show x
<interactive>:4:1:
No instance for (Show (IO Int)) arising from a use of ‘show’
In the expression: show x
In an equation for ‘it’: it = show x
当我在 ghci 中输入 x
时发生了什么?
如果您在 GHCi 中输入 IO t
类型的表达式,它会解包并打印结果值。也就是说,如果您输入 ioExp
,GHCi 会执行 val <- ioExp; print val
(而如果您输入非 IO 表达式 exp
,GHCi 会执行 print exp
)。
您不能 show
执行 IO Int
操作。该操作可能需要执行副作用以产生 Int
,例如向用户询问此类数字。相反,show
的类型承诺 return 和 String
,即没有任何副作用的纯字符串。
如果需要,您可以定义自己的 show
有效变体:
showIO :: Show a => IO a -> IO String
showIO = fmap show
请注意上面的结果不是纯字符串,而是包含在 IO
monad 中,它应该是这样。