计算工作流程问题

发布于 2024-10-02 19:32:44 字数 934 浏览 2 评论 0原文

尝试遵循专家 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 ()

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

谢谢!

trying to follow example in the expert f# book, and having an issue with the workflows...the code is as follows:

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 ()

problem is , when all values are true, i get as expected, a Some(true, true, true), but if one of the values passed in is false, foo is null (!). Anyone ftw?

thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

瞎闹 2024-10-09 19:32:44

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

member x.Zero() = fail

到您的构建器中,然后您可以编写测试,因为

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

这对我来说更干净一些。

This is just because None is actually represented as null at runtime (see the remarks on the Option<'T> page on MSDN). Also, note that you can add

member x.Zero() = fail

to your builder, and then you can write test as

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

which is a little cleaner to my eyes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文