如何创建一个支持单步执行的F#工作流程?

时间:2010-01-08 09:22:54

标签: f# workflow computation-expression

我想创建一个构建表达式的构建器,在每个步骤之后返回类似延续的表达式。

这样的事情:

module TwoSteps = 
  let x = stepwise {
    let! y = "foo"
    printfn "got: %A" y
    let! z = y + "bar"
    printfn "got: %A" z
    return z
  }

  printfn "two steps"
  let a = x()
  printfn "something inbetween"
  let b = a()

其中'let a'行返回包含稍后要评估的其余表达式的内容。

对于每个步骤,使用单独的类型执行此操作非常简单,但当然不是特别有用:

type Stepwise() =
  let bnd (v: 'a) rest = fun () -> rest v
  let rtn v = fun () -> Some v
  member x.Bind(v, rest) = 
    bnd v rest
  member x.Return v = rtn v

let stepwise = Stepwise()

module TwoSteps = 
  let x = stepwise {
    let! y = "foo"
    printfn "got: %A" y
    let! z = y + "bar"
    printfn "got: %A" z
    return z
  }

  printfn "two steps"
  let a = x()
  printfn "something inbetween"
  let b = a()

module ThreeSteps = 
  let x = stepwise {
    let! y = "foo"
    printfn "got: %A" y
    let! z = y + "bar"
    printfn "got: %A" z
    let! z' = z + "third"
    printfn "got: %A" z'
    return z
  }

  printfn "three steps"
  let a = x()
  printfn "something inbetween"
  let b = a()
  printfn "something inbetween"
  let c = b()

结果正是我要找的:

two steps
got: "foo"
something inbetween
got: "foobar"
three steps
got: "foo"
something inbetween
got: "foobar"
something inbetween
got: "foobarthird"

但我无法弄清楚这种情况的一般情况。

我想要的是能够将事件提供给此工作流程,因此您可以编写如下内容:

let someHandler = Stepwise<someMergedEventStream>() {
  let! touchLocation = swallowEverythingUntilYouGetATouch()
  startSomeSound()
  let! nextTouchLocation = swallowEverythingUntilYouGetATouch()
  stopSomeSound()
}

让事件触发移动到工作流程的下一步。 (特别是,我想在iPhone上使用MonoTouch - F#进行此类操作。绕过objc选择器会让我疯狂。)

2 个答案:

答案 0 :(得分:2)

你的实现的问题是它为每次调用Bind返回“unit - &gt;'a”,所以你会得到不同数量的步骤的不同类型的结果(一般来说,这是一个可疑的定义monad /计算表达式)。

正确的解决方案应该是使用其他类型,这可以用任意数量的步骤表示计算。您还需要区分两种类型的步骤 - 一些步骤仅评估计算的下一步,一些步骤返回结果(通过return关键字)。我将使用seq<option<'a>>类型。这是一个惰性序列,因此读取下一个元素将评估计算的下一步。该序列将包含None值,但最后一个值除外,该值为Some(value),表示使用return返回的结果。

您实施中的另一个可疑事项是非标准类型的Bind成员。 bind将一个值作为第一个参数这一事实意味着您的代码看起来更简单一些(您可以编写let! a = 1)但是,您无法组成逐步计算。您可能希望能够写下:

let foo() = stepwise { 
  return 1; }
let bar() = stepwise { 
  let! a = foo()
  return a + 10 }

我上面描述的类型也允许你写这个。获得该类型后,您只需要在实现中遵循BindReturn的类型签名,您就会得到:

type Stepwise() = 
  member x.Bind(v:seq<option<_>>, rest:(_ -> seq<option<_>>)) = seq {
    let en = v.GetEnumerator()
    let nextVal() = 
      if en.MoveNext() then en.Current
      else failwith "Unexpected end!" 
    let last = ref (nextVal())
    while Option.isNone !last do
      // yield None for each step of the source 'stepwise' computation
      yield None
      last := next()
    // yield one more None for this step
    yield None      
    // run the rest of the computation
    yield! rest (Option.get !last) }
  member x.Return v = seq { 
    // single-step computation that yields the result
    yield Some(v) }

let stepwise = Stepwise() 
// simple function for creating single-step computations
let one v = stepwise.Return(v)

现在,让我们看看使用类型:

let oneStep = stepwise {
  // NOTE: we need to explicitly create single-step 
  // computations when we call the let! binder
  let! y = one( "foo" ) 
  printfn "got: %A" y 
  return y + "bar" } 

let threeSteps = stepwise { 
  let! x = oneStep // compose computations :-)
  printfn "got: %A" x 
  let! y = one( x + "third" )
  printfn "got: %A" y
  return "returning " + y } 

如果要逐步运行计算,可以简单地迭代返回的序列,例如使用F#for关键字。以下还打印步骤的索引:

for step, idx in Seq.zip threeSteps [ 1 .. 10] do
  printf "STEP %d: " idx
  match step with
  | None _ -> ()
  | Some(v) -> printfn "Final result: %s" v

希望这有帮助!

PS:我发现这个问题非常有趣!您是否介意我将我的答案添加到我的博客(http://tomasp.net/blog)的博客文章中?谢谢!

答案 1 :(得分:1)

Monads和计算建设者让我感到困惑,但我已经改编了earlier SO post中的一些东西。也许一些零碎的东西可以使用。

下面的代码包含一个操作队列,以及一个表单,其中Click事件侦听操作队列中可用的下一个操作。下面的代码是连续4个动作的示例。在FSI中执行它并开始单击表单。

open System.Collections.Generic
open System.Windows.Forms

type ActionQueue(actions: (System.EventArgs -> unit) list) =
    let actions = new Queue<System.EventArgs -> unit>(actions) //'a contains event properties
    with
        member hq.Add(action: System.EventArgs -> unit) = 
           actions.Enqueue(action)
        member hq.NextAction = 
            if actions.Count=0 
                then fun _ -> ()
                else actions.Dequeue()

//test code
let frm = new System.Windows.Forms.Form()

let myActions = [
    fun (e:System.EventArgs) -> printfn "You clicked with %A" (e :?> MouseEventArgs).Button
    fun _ -> printfn "Stop clicking me!!"
    fun _ -> printfn "I mean it!"
    fun _ -> printfn "I'll stop talking to you now."
    ]

let aq = new ActionQueue(myActions)

frm.Click.Add(fun e -> aq.NextAction e)

//frm.Click now executes the 4 actions in myActions in order and then does nothing on further clicks
frm.Show()

您可以点击该表单4次,然后点击进一步没有任何反应。 现在执行以下代码,表单将再响应两次:

let moreActions = [
    fun _ -> printfn "Ok, I'll talk to you again. Just don't click anymore, ever!"
    fun _ -> printfn "That's it. I'm done with you."
    ]

moreActions |> List.iter (aq.Add)