Neu*_*onQ 2 monads haskell types algebraic-data-types io-monad
什么是data此Haskell type语句的等效语句:
type CWIO a = CWorld -> (a, CWorld)
Run Code Online (Sandbox Code Playgroud)
......这会让我写:
instance Monad CWIO where
(action1 >>= action2) w0 =
let (x1, w1) = action1 w0
(x2, w2) = action2 x1 w1
in (x2, w2)
return a = \world -> (a, world)
Run Code Online (Sandbox Code Playgroud)
CWorld:
data CWorld = CWorld {
cin :: String,
cout :: String
}
Run Code Online (Sandbox Code Playgroud)
我正在通过实际构建一个真正有效的"虚拟IO monad"(在其"虚拟世界"中)来寻求"真正理解"monad.对于monad的概念有某种"通过构建/工程理解/解释",因为我是那种需要自己从头开始构建东西才能真正理解"某事"的人,所以我要去这里路线相同.整个代码上下文在这里https://gist.github.com/NeuronQ/11119444/adbf0a9d6d17d4231d7ec68f565203f8dd75f702,但对于任何有经验的Haskell程序员来说,它可能看起来毫无意义和"残酷".
你想要的东西
newtype CWIO a = CWIO { unCWIO :: CWorld -> (a, CWorld) }
Run Code Online (Sandbox Code Playgroud)
这将允许您定义适当的实例,并使用CWIO和unCWIO在包装的CWIO计算和未包装的底层函数之间来回移动.newtype是一个data为单个构造函数的包装器量身定制和优化的变体.
请注意,通过采用这样的定义,CWIO最终会得到与State专门用于CWorld状态的monad 相同的东西.