Haskell MonadIO与IO

时间:2018-09-18 13:11:28

标签: haskell

两者之间有什么区别?

recompile :: MonadIO m => Bool -> m Bool
recompile :: Bool -> IO Bool

1 个答案:

答案 0 :(得分:7)

类型forall m. MonadIO m => Bool -> m BoolBool -> IO Bool是同构的:

{-# LANGUAGE RankNTypes #-}
import Control.Monad.IO.Class

from :: (forall m. MonadIO m => Bool -> m Bool) -> (Bool -> IO Bool)
from act = act

to :: (Bool -> IO Bool) -> (forall m. MonadIO m => Bool -> m Bool)
to act = liftIO . act

Not all types involving IO are isomorphic to a version that replaces IO with a constrained m, though.

通常,当人们觉得通过调用代码分散MonadIO m会很烦人,或者需要使用其他m ~ IO样式约束时,通常使用liftIO而不是mtl m;并在简化API时使用m ~ IO而不是MonadIO m(其中MonadIO m会增加复杂性,因此不受欢迎),或者在处理派生或异常处理时(其中{{1} }由于链接问题中讨论的原因而无法实现。