我正在尝试在 OCaml 中使用 Writer monad。
module Writer : Monad = struct
type 'a t = 'a * string
let return x = (x, "")
let (>>=) m f =
let (x, s1) = m in
let (y, s2) = f x in
(y, s1 ^ s2)
end
下面的语句有效。
Writer.(>>=) (Writer.return 2) (fun x -> Writer.return 1);;
但下面的声明没有。
Writer.(>>=) (Writer.return 2) (fun x -> (x, "inc"));;
Error: This expression has type 'a * 'b but an expression was expected of type
'c Writer.t
我试过了
Writer.(>>=) (Writer.return 2) (fun x -> ((x, "inc") : int Writer.t))
Error: This expression has type 'a * 'b but an expression was expected of type
int Writer.t
我在这里做错了什么?如何将值提升到 OCaml 中的 monad?