【问题标题】:Using custom computation expression operator inside match statement在 match 语句中使用自定义计算表达式运算符
【发布时间】:2015-10-11 19:51:45
【问题描述】:

现在我正在试验 F# 计算表达式。总的想法是返回控制机制来驱动在递归函数调用的每一步从计算表达式构建之后执行的动作。整个例子可以看here

使用以下示例:

let rec loop () =
    actor {
        let! msg = m.Receive ()
        match msg with
        | "stop" -> return 0        // expected result: Return (0)
        | "unhandled" -> unhandled  // expected result: Unhandled 
        | x -> 
            mailbox.Sender() <! x
            return! loop ()         // expected result: (Become(fun m -> loop ()))
    }
loop ()

不幸的是,这以 unhandled 上的编译时错误结束:自定义操作不能与“use”、“try/with”、“try/finally”、“if/then/else”结合使用此计算表达式中的 ' 或 'match' 运算符

是否可以在 match 语句中以任何方式使用自定义运算符?

【问题讨论】:

  • 什么是unhandled?并且 - 假设它也是s of the right type - why don't you use return` 或 return!
  • unhandled 是自定义运算符。一般来说,Return 和 ReturnFrom 能够返回 ReturnBecome 类型的可区分联合,具体取决于表达式是值还是递归函数调用。此 DU 稍后用于应用​​附加逻辑。我想做的是添加额外的 DU 类型Unhandled,它应用了另一种逻辑。

标签: f# computation-expression


【解决方案1】:

我不确定actor 计算的细节是什么,但如果Unhandled 是底层计算类型的值,您当然可以使用return! 生成它

在不知道细节的情况下,我认为这样的事情应该起作用:

match msg with
| "stop" -> return 0
| "unhandled" -> return! Unhandled
| x -> 
    mailbox.Sender() <! x
    return! loop ()   

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 2011-11-02
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多