简体   繁体   English

F# 绑定选项和任务

[英]F# bind option and a task

I want to to replicate the following C# code:我想复制以下 C# 代码:

var things = url is null ? null : await GetThings(url);

What I got is:我得到的是:

 task {
            match urlOption with
            | None -> return None
            | Some url ->
                let! things = this.GetThings(url)
                return things |> Some
        }

I excpected to be able to do something like:我期望能够做类似的事情:

let! things = url >>= this.GetThings 

Am I missing some operator declarations?我错过了一些运营商声明吗? Probably, but do I need to write them on my own or is there a library?可能,但是我需要自己编写它们还是有图书馆?

I found Fsharp.Plus but I have no idea whether this does not have what I want, or I just do it wrong.我找到了 Fsharp.Plus但我不知道这是否没有我想要的,或者我做错了。

Yes, you can do it with F#+ but you need to wrap it in an OptionT :是的,您可以使用 F#+ 来完成,但您需要将其包装在OptionT中:

#r "nuget: FSharpPlus"

open System
open System.Threading.Tasks
open FSharpPlus
open FSharpPlus.Data

let x = Task.FromResult (Some 42)
let f x = Task.FromResult (Some x)

let y =
    OptionT x
    >>= (OptionT << f) 
    |> OptionT.run

Then you can use the >>= operator as demonstrated above or the generic `monad`` computation expression.然后你可以使用上面演示的>>=运算符或通用的 `monad` 计算表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM