gpt4 book ai didi

f# - 计算工作流的问题

转载 作者:行者123 更新时间:2023-12-02 00:36:55 26 4
gpt4 key购买 nike

尝试按照专家 f# 书中的示例进行操作,但工作流程存在问题...代码如下:

type Attempt<'a> = option<'a>
let succeed x = Some (x)
let fail = None

let bind p rest =
match p with
| None -> fail
| Some r -> rest r

let delay f = f()

type AttemptBuilder() =

member b.Return (x) = succeed x
member b.Bind (p, rest) = bind p rest
member b.Delay (f) = delay f
member b.Let (p, rest):Attempt<'a> = rest p //'
member b.ReturnFrom x = x


// using it:
let attempt = new AttemptBuilder()

let test foo =
attempt {
if not foo then return! fail else return foo
}

let check () =
attempt {

let! n1 = test true
let! n2 = test false
let! n3 = test true
let foo = n1,n2,n3
return foo
}
let foo = check ()

问题是,当所有值都为真时,我得到预期的 Some(true, true, true),但如果传入的值之一为假,则 foo 为 null (!)。有人吗?

谢谢!

最佳答案

这只是因为None实际上表示为 null在运行时(请参阅 Option<'T> page on MSDN 上的备注)。另请注意,您可以添加

member x.Zero() = fail

给你的构建器,然后你可以将测试写成

let test x = attempt { if x then return foo }

这对我来说更干净一些。

关于f# - 计算工作流的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4200319/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com