如何在 ADT 或记录语法上使用 Monadic 绑定运算符
How to use Monadic binding operator on ADT or record syntax
你好有人可以解释一下你如何在代数数据类型或记录语法的字段上使用单子绑定运算符吗?
例如
data M = M {myfield :: Int}
data N = N Int
所以对于 M
,如果我想从 IO Int
动作中提取值到 myfield
中,我似乎不能说:
a = M { return 3 >>= value }
另外,如何绑定 N
类型?
该字段的类型为 Int
,因此您无法将其绑定到任何其他类型,例如 IO Int
。
但是,您可以 运行 IO Int
操作,获得 Int
回报,然后使用它。
foo :: IO Something
foo = do
i <- return 3 -- run your (IO Int) action
let a = M { myfield = i }
...
-- at the end, you have to use an (IO Something) action
相反,您可以将 N
转换为 M
,如下所示
convertNtoM :: N -> M
convertNtoM (N i) = M { myfield = i }
同样,这不会将 N
值绑定到 myfield
,而是将整数 "inside" 绑定到 N
值。
如果有多个操作要 运行,并且要填写许多字段,则可以使用 "applicative style".
data K = K Int Int Int Int
action :: IO Int
action = return 3
foo :: IO K
foo = K <$> action <*> action <*> action <*> action
你好有人可以解释一下你如何在代数数据类型或记录语法的字段上使用单子绑定运算符吗?
例如
data M = M {myfield :: Int}
data N = N Int
所以对于 M
,如果我想从 IO Int
动作中提取值到 myfield
中,我似乎不能说:
a = M { return 3 >>= value }
另外,如何绑定 N
类型?
该字段的类型为 Int
,因此您无法将其绑定到任何其他类型,例如 IO Int
。
但是,您可以 运行 IO Int
操作,获得 Int
回报,然后使用它。
foo :: IO Something
foo = do
i <- return 3 -- run your (IO Int) action
let a = M { myfield = i }
...
-- at the end, you have to use an (IO Something) action
相反,您可以将 N
转换为 M
,如下所示
convertNtoM :: N -> M
convertNtoM (N i) = M { myfield = i }
同样,这不会将 N
值绑定到 myfield
,而是将整数 "inside" 绑定到 N
值。
如果有多个操作要 运行,并且要填写许多字段,则可以使用 "applicative style".
data K = K Int Int Int Int
action :: IO Int
action = return 3
foo :: IO K
foo = K <$> action <*> action <*> action <*> action