gpt4 book ai didi

ocaml - 使用 monad 简化重复模式

转载 作者:行者123 更新时间:2023-12-05 01:22:38 25 4
gpt4 key购买 nike

我实际上不确定这对 monad 是否可行,或者是否应该用它们来完成,我正在寻找一个解决方案,而不是如果 monad 不是解决方案则用 monad 解决它。

假设我有以下代码(经过简化,但思路就在这里):

module IM = Map.Make (Int)

let f k v m =
if IM.mem k m then (m, true)
else (IM.add k v m, false)

let a =
let m = IM.empty in
let m, res = f 0 "Zero" m in
if res then
let m, res = f 1 "One" m in
if res then f 2 "Two" m else (m, res)
else (m, res)

我要重复多次:

let value, boolean = function application to value and other values in 
if boolean then another function application to the new value and other values (not the same as the first one)
else the result

这意味着这些函数不一定具有相同的类型,但它们都返回一个a IM.t * bool(a 对每个函数都是相同的类型)

我想知道是否可以创建一个允许我这样做的内联运算符。

我试过类似的方法:

module EqMonad = struct
let ( let* ) (t, res) f2 = if res then f2 t else (t, false)
let return t = t
end

但这显然行不通,因为 f2 接受多个参数但需要接收 t 作为它的最后一个参数。

我想我可以这样总结我的问题:

Is it possible to have monads wrapping variadic functions?

最佳答案

您的解决方案有效(return 更正为 monadic return)并且是错误 monad 的受限版本:

let return x = x, true
let a =
let m = IM.empty in
let* m = f 0 "Zero" m in
let* m = f 1 "One" m in
let* m = f 2 "Two" m in
return m

但是,由于控制流从不依赖于 m 的值,这表明使用常规函数可能更简单:


let rec add_first_fresh m l = match l with
| [] -> None
| (k,v):: q ->
if IM.mem k m then add_first_fresh m q
else Some (IM.add k v m)

let a = add_first_fresh IM.empty
[0, "Zero";
1, "One";
2, "Two"
]

关于ocaml - 使用 monad 简化重复模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73634126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com