为什么专门化单子的类型会导致错误



以下计算顺序正常工作:

type Monad_1 () =
    member M.Bind (so : 'T option, bf : 'T -> 'T option) : 'T option =
        match so with
        | Some s -> bf s
        | None -> None
    member M.Delay (df : unit -> 'T) : 'T = // SEE CORRECTION 1
        df ()
    member M.Return (rv : 'T) : 'T option =
        Some rv
let test_1 () : unit =
    let m_1 = Monad_1 ()
    let cero =
        m_1 {
            let x1 = 10
            let! x2 = Some 20
            let! x3 = Some 30
            return x1 + x2 + x3}
    match cero with
    | Some cer -> printfn "%d" cer
    | None -> printfn "None"
test_1 () // Output: 60

现在假设我采用相同的monad并将其特化为整数类型:

type Monad_2 () =
    member M.Bind (so : int option, bf : int -> int option) : int option =
        match so with
        | Some s -> bf s
        | None -> None
    member M.Delay (df : unit -> int) : int = // SEE CORRECTION 2
        df ()
    member M.Return (rv : int) : int option =
        Some rv
let test_2 () : unit =
    let m_2 = Monad_2 ()
    let cero =
        m_2 {
            let x1 = 10
            let! x2 = Some 20 // ERROR HERE: This expression was expected to have type int, but here has type int option
            let! x3 = Some 30
            return x1 + x2 + x3}
    match cero with
    | Some cer -> printfn "%d" cer
    | None -> printfn "None"
test_2 () // ERROR
谁能解释一下我理解上的错误吗?即使是提示也是有帮助的,以防写一个完整的解释需要很长时间。

根据Mauricio Scheffer上面的评论,Delay的签名是不正确的。

修正1

M.Delay<'T> (df : unit -> 'T option) : 'T option

校正2

M.Delay (df : unit -> int option) : int option

相关内容

  • 没有找到相关文章

最新更新