Stream Monad:绑定和零返回

问题描述 投票:0回答:0

给定这个流 monad 作为解决方案:

module StMonad = struct 
  type 'a stream = Nil | Cons of 'a * ( unit -> 'a stream)
  let return v = Cons(v, fun() -> Nil)
  let rec bind v f =
    match v with 
    | Nil -> Nil
    | Cons(h, t) -> let res = (f h) in 
        match res with
        | Nil -> Nil
        | Cons(r_h, _) -> Cons(r_h, fun () -> bind (t()) f)
  let (>>=) = bind
end

我对

bind
操作有些困惑,这部分:

| Cons(h, t) -> let res = (f h) in 
        match res with
        | Nil -> Nil

不应该是:

Nil -> bind (t()) f
,否则它将停止并且不会移动到流的其余部分的递归,你能澄清一下吗?

更新:

此外,我正在考虑使用

bind
作为映射函数,因为我通过了
f
而没有返回
Nil
,并且我正在考虑使用
bind
作为过滤函数,给定
f
返回
Nil 
,从而跳过不需要的元素,对吗?

functional-programming ocaml monads
© www.soinside.com 2019 - 2024. All rights reserved.