F#自定义计算工作流程

时间:2013-08-19 17:08:21

标签: f# monads monad-transformers

给出结果类型

type Result<'t> = OK of 't | Error of string 

我有这些函数都返回Async&lt;结果&LT;'T&GT; &GT;结合这样的东西:

let a = async { return Result.OK 1000 }
let b = async { return Result.Error "some message" }

let sum x y = 
    async {
        let! r1 = x
        match r1 with
        | Result.OK v1 -> 
             let! r2 = y
             match r2 with
             | Result.OK v2 -> return v1 + v2
             | Result.Error msg -> return Result.Error msg
        | Result.Error msg -> return Result.Error msg
    }

这段代码看起来很糟糕,所以我希望这样:

type Result = Ok of int | Error of string

type MyMonadBuilder() =
    member x.Bind (v,f) = 
        async { 
            let! r = v
            match r with
            | Ok r' -> return! f r'
            | Error msg -> return Error msg
        }

    member x.Return v = async {return Ok v }

    member x.Delay(f) = f()

let mymonad = MyMonadBuilder()
let runMyMonad = Async.RunSynchronously

let a = mymonad { return 10 }
let b = mymonad { return 20 }

let c = 
    mymonad { 
        return Result.Error "Some message"
        //??? The above doesn't work but how do I return a failure here?
    }

let d = 
    async {
        return Ok 1000
    } 
    //how to wrap this async with mymonad such that I can use it together with my other computation expressions?

let sum x y = 
    mymonad {
        let! v1 = x
        let! v2 = y
        return v1 + v2
    }

[<EntryPoint>]
let main argv = 
    let v = sum a b |> runMyMonad
    match v with
    | Ok v' -> printfn "Ok: %A" v'
    | Error msg -> printf "Error: %s" msg

    System.Console.Read() |> ignore
    0 

所以问题是:

  1. 如何编写函数c使其在mymonad中返回错误?
  2. 如何编写函数d,使其包含与mymonad的异步?
  3. 如何以与Async类似的方式使我的monad参数化?
  4. ......这样我就可以写了

    let f (a:MyMonad<int>) (b:MyMonad<string>) = ...
    

    更新:

    此外,我想并行运行几个mymonad操作,然后查看结果数组,看看错误和成功是什么。出于这个原因,我认为使用例外不是一个好主意。

    另外,关于问题3,我的意思是让我的类型参数化和不透明,使得调用者不知道/不关心他们正在处理异步。我编写monad的方式调用者总是可以使用Async.RunSynchronously来运行mymonad表达式。

    更新2:

    到目前为止,我最终得到了以下内容:

    1. 我为MyMonadBuilder的每个成员使用显式类型
    2. 我将ReturnFrom添加到MyMonadBuilder。我用这个函数来包装Async&lt;结果&LT;'T&GT; &GT;
    3. 我添加了诸如failwith之类的辅助函数,它创建了一个带有错误值的mymonad
    4. 代码如下所示:

      type MyMonad<'t> = 't Result Async
      
      type MyMonadBuilder() =
          member x.Bind<'t> (v,f) : MyMonad<'t>= 
              async { 
                  let! r = v
                  match r with
                  | Ok r' -> return! f r'
                  | Error msg -> return Error msg
              }
      
          member x.Return<'t> v  : MyMonad<'t> = async {return Ok v }
          member x.ReturnFrom<'t> v  : MyMonad<'t> = v
      
          member x.Delay(f) = f()
      
      let failwith<'t> : string -> MyMonad<'t> = Result.Error >> async.Return
      

      这看起来相当不错。谢谢!

2 个答案:

答案 0 :(得分:4)

异步工作流通过异常自动支持错误处理,因此惯用解决方案只是使用异常。如果要区分某些特殊类型的错误,则可以定义自定义异常类型:

exception MyError of string

// Workflow succeeds and returns 1000
let a = async { return 1000 }
// Workflow throws 'MyError' exception
// (using return! means that it can be treated as a workflow returning int)
let b = async { return! raise (MyError "some message") }

// Exceptions are automatically propagated
let sum = async {
  let! r1 = a
  let! r2 = b
  return r1 + r2 }

如果要处理异常,可以在异步工作流中使用try ... with MyError msg -> ...

可以定义一个自定义计算构建器,它使用代数数据类型(例如Result)重新实现它,但除非你有一些非常好的理由这样做,我会不推荐这种方法 - 它不适用于标准库,它非常复杂,不适合一般的F#风格。

在计算表达式中,值的类型为Async<Result<'T>>return会自动将类型为'T的参数包装在返回Ok的异步工作流中。如果要构造表示失败的值,可以使用return!并创建返回Result.Error的异步工作流。你可能需要这样的东西:

let c = mymonad { 
  return! async.Return(Result.Error "Some message")
}
let d = mymonad {
    return 1000
} 

但正如我所说,使用例外是一种更好的方法。

编辑:要回答评论中的问题 - 如果您有许多异步计算,您仍然可以将最终结果包装在自定义类型中。但是,您不需要重建整个异步工作流库 - 基本操作中的错误仍然可以使用标准异常处理:

// Primitive async work that may throw an exception
let primitiveAsyncWork = async { ... } 

// A wrapped computation that returns standard Option type
let safeWork = async {
  try 
    let! res = primitiveAsyncWork
    return Some res
  with e -> return None }

// Run 10 instances of safeWork in parallel and filter out failed computations
async { let! results = [ for i in 0 .. 9 -> safeWork ] |> Async.Parallel
        return results |> Seq.choose id }

答案 1 :(得分:3)

我的asyncChoice库中的ExtCore工作流已经实现了这一点 - 它可以在NuGet上使用,因此您需要做的就是添加对项目的引用,打开ExtCore.Control命名空间您的源文件,并开始编写如下代码:

open ExtCore.Control

let asyncDivide100By (x : int) =
    asyncChoice {
        if x = 0 then
            return! AsyncChoice.error "Cannot divide by zero."
        else
            return (100 / x)
    }

let divide100By (x : int) =
    let result =
        asyncDivide100By x
        |> Async.RunSynchronously

    match result with
    | Choice1Of2 result ->
        printfn "100 / %i = %i" x result
    | Choice2Of2 errorMsg ->
        printfn "An error occurred: %s" errorMsg


[<EntryPoint>]
let main argv =
    divide100By 10
    divide100By 1
    divide100By 0

    0   // Exit code

asyncChoice是使用F#Core库中的标准Async<'T>Choice<_,_>类型构建的,因此您不应该遇到任何兼容性问题。