为了更多地了解计算表达式的工作方式,我尝试编写一个构建器,它在计算then语句的if块之后跳过表达式的其余部分,从而工作流本身将计算为true。如果没有计算到false的if语句,工作流应该返回true。
例如:
let mutable x = 0
let result =
earlyExit {
if false then x <- 99
if true then x <- 33
if true then x <- 11
}在这里,result应该是true,x应该是33。
我最近得到的是:
type EarlyExitBuilder () =
member this.Combine (a, b) = a || b ()
member this.Delay fn = fn
member this.Run fn = fn ()
member this.Zero () = false..。这就导致了工作流对false的评估,x对11的评估。
使用我的示例中的语法是否可行?
发布于 2016-07-13 15:42:20
给出您所要寻找的行为的最小更改可能是将return添加到计算中-- return构造可以返回true并提前终止计算:
let mutable x = 0
let result =
earlyExit {
if false then return x <- 99
if true then return x <- 33
if true then return x <- 11
}这将计算为true,x的值将是33。计算生成器与您的相同,其他Return成员返回true:
type EarlyExitBuilder () =
member this.Combine (a, b) = a || b ()
member this.Delay fn = fn
member this.Run fn = fn ()
member this.Zero () = false
member this.Return( () ) = true正如其中一个引用的答案中提到的,这与我的命令式计算生成器有些关联,它允许您使用命令式return和带中断和继续的扩展版本。
发布于 2016-07-13 02:54:40
我认为使用您提议的语法没有任何好的方法;在计算表达式的内部,类似于
if c then e将被编译成类似于
if c then
e
builder.Zero()
else
builder.Zero()因此,上下文无法区分哪个分支被采用。
https://stackoverflow.com/questions/38340711
复制相似问题