【发布时间】:2017-05-16 03:32:07
【问题描述】:
我试图直接实现这个Maybe monad。因此,如果中间步骤之一是Nothing,则基本上整个表达式的计算结果为Nothing。
type Maybe<'a> =
| Just of 'a
| Nothing
type MaybeBuilder () =
member this.Combine ((first, second) : Maybe<'a> * Maybe<'b>) : Maybe<'b> =
printfn "Combine called"
match first with
| Nothing -> Nothing
| _ ->
match second with
| Nothing -> Nothing
| _ as a -> a
member this.Zero () = Just ()
member this.Bind((m, f) : Maybe<'a> * ('a -> Maybe<'b>)) =
printfn "Bind called"
match m with
| Nothing -> Nothing
| Just a -> f a
let MaybeMonad = MaybeBuilder()
let foobar =
MaybeMonad {
let! foo = Just "foo"
Just 1
Nothing
}
我预计foobar 会被翻译成Just "foo" >>= fun foo -> Combine(Just 1, Nothing),但是Combine 没有被调用。
【问题讨论】: