我可以在F#中同时使用不同的工作流程吗? [英] Can I use different workflows simultaneously in F#?
问题描述
我需要传递我的状态,同时能够与可能的工作流链接功能.有两种方法可以共享相同的上下文吗?如果没有,怎么办?
更新:
好吧,我有一个状态,表示要在数据库中创建的实体的可用ID的一部分.因此,一旦获取了ID,就必须将状态转换为具有下一个可用ID的较新状态,然后将其丢弃,以使任何人都无法再次使用它.我不想为了惯用而改变状态. State monad隐藏了转换并传递了状态,因此看起来就像是要走的路.一旦状态工作流就位,我将无法使用Maybe工作流,这是我在各处使用的东西.
如上一个答案所述,在F#(Haskell中的Monads)中组合工作流的一种方法是使用一种称为Monad Transformers的技术.
在F#中,这确实很棘手,这里是一个处理该技术的项目. >
可以使用该库通过自动组合State和Maybe(选项)来编写上一个答案的示例:
#r @"c:\packages\FSharpPlus-1.0.0\lib\net45\FSharpPlus.dll"
open FSharpPlus
open FSharpPlus.Data
// Stateful computation
let computation =
monad {
let! x = get
let! y = OptionT (result (Some 10))
do! put (x + y)
let! x = get
return x
}
printfn "Result: %A" (State.eval (OptionT.run computation) 1)
这是另一种选择,而不是创建自定义工作流,而是使用将自动推断出的通用工作流(a-la Haskell).
I need my state to be passed along while being able to chain functions with the maybe workflow. Is there a way for 2 workflows to share the same context? If no, what is the way of doing it?
UPDATE:
Well, I have a state that represents a segment of available ID's for the entities that I am going to create in the database. So once an ID is acquired the state has to be transformed to a newer state with the next available ID and thrown away so that nobody can use it again. I don't want to mutate the state for the sake of being idiomatic. The State monad looks like a way to go as it hides the transformation and passes the state along. Once the state workflow is in place I cannot use the Maybe workflow which is something I use everywhere.
As stated in the previous answer, one way to combine workflows in F# (Monads in Haskell) is by using a technique called Monad Transformers.
In F# this is really tricky, here is a project that deals with that technique.
It's possible to write the example of the previous answer by automatically combining State and Maybe (option), using that library:
#r @"c:\packages\FSharpPlus-1.0.0\lib\net45\FSharpPlus.dll"
open FSharpPlus
open FSharpPlus.Data
// Stateful computation
let computation =
monad {
let! x = get
let! y = OptionT (result (Some 10))
do! put (x + y)
let! x = get
return x
}
printfn "Result: %A" (State.eval (OptionT.run computation) 1)
So this is the other alternative, instead of creating your custom workflow, use a generic workflow that will be automatically inferred (a-la Haskell).
这篇关于我可以在F#中同时使用不同的工作流程吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!