5

我正在编写一个本质上实现State monad的计算表达式,并且我正在尝试使用for表达式。

我可以使用样板函数forLoop甚至MBuilder.For(),它们都返回一个M<seq<'U>, _>可以通过进一步let!表达处理的 nice 。但是当我尝试对for表达式做同样的事情时,它无法编译告诉我里面的表达式for必须 return unit

对于无法缩小的大代码块,我感到很抱歉。

type M<'T, 'E> = 'T * 'E                 // Monadic type is a simple tuple
type MFunc<'T, 'U, 'E> = 'T -> M<'U, 'E> // A function producing monadic value

// typical boilerplate functions
let bind (x: M<'T, 'E>) (f: MFunc<'T, 'U, 'E>) : M<'U, 'E> =
    let a, s = x
    let b, s1 = f a
    b, s1 + s
let combine (e1: M<'T, 'E>) (e2: M<'U, 'E>) : M<'U, 'E> = bind e1 (fun _ -> e2)
let delay f = (fun () -> f())()

// These two are explained below
let combineList (e1: M<'T, 'E>) (e2: M<'T seq, 'E>) : M<'T seq, 'E> =
    bind
        e1
        (fun x1 ->
            let e2body, e2state = e2
            seq{yield! e2body; yield x1}, e2state
        )
let forLoop (xs: seq<'T>) (f: MFunc<'T, 'U, 'E>) : M<seq<'U>, 'E> =
    Seq.fold
        (fun s x -> combineList (f x) s)
        (Seq.empty<'U>, 0)
        xs

// Builder class
type MBuilder() =
    member this.Bind (x: M<'T, 'E>, f: MFunc<'T, 'U, 'E>) : M<'U, 'E> = bind x f
    member this.Return(a) = a, 0
    member this.Combine(e1,e2) = combine e1 e2
    member this.Delay(f) = delay f
    member this.Zero() = (), 0
    member this.For (xs: seq<'T>, f: MFunc<'T, 'U, 'E> ) : M<seq<'U>, 'E> = forLoop xs f
let stateful = new MBuilder()

let mTest = stateful {
    // below is the typical use, just for example
    let! var1 = "q", 3
    let! var2 = true, 4
    // so far so good, the monad returns ("test", 7)
    return "test"
    }

现在,我正在尝试使用循环。以下三个调用按预期工作,增加状态的次数与myList. 他们还返回一个美丽的string seq,显然除了最后一个电话:

    let myList = ["one"; "two"; "three"] // define test data

    let! var3 = stateful.For(myList, (fun x -> x, 1))
    let! var4 = forLoop myList (fun x -> x, 1)

    // No return value, as expected
    for str in myList do
        let! _ = str, 1
        return ""

但以下内容无法编译:error FS0001: This expression was expected to have type M<'a,int> but here has type unit

    let! var5 =
        for str in myList do
            let! _ = str, 1
            return ""

所以我的问题是 -我做错了什么?

我也对这里For描述的两个重载以及如何使用它们感到有点困惑。

4

1 回答 1

11

您尝试编写的代码在语法上不是有效的计算表达式。该语法不允许elet! v = e.

如果要使用嵌套计算表达式,则必须编写:

let mtest = stateful {
  let! var5 = 
    stateful { for str in myList do 
                 let! _ = str, 1 
                 return "" }
  return "something here" }

这应该可以回答您的直接问题,但是我发现您的定义有很多令人困惑的地方:

  • 你的类型For令人困惑。它应该是seq<'T> -> ('T -> M<'R>) -> M<'R>(如果您的 monad 可以组合多个结果)或seq<'T> -> ('T -> M<unit>) -> M<unit>(如果您的计算只返回一个值)

  • 您有时在结果中使用seq<'T>inside M<_>(in For),但有时您的 monad 只返回一个值。您应该在任何地方使用相同的单子类型。

  • 该构造可以用和For来定义。除非您正在做一些特别的事情,否则这是最好的方法。请参阅F# 规范中的示例ZeroCombine

如果您想要更详细的文档,请查看这篇文章,其中描述了各种选项。

于 2012-06-28T20:51:17.920 回答