我正在编写一个本质上实现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
描述的两个重载以及如何使用它们感到有点困惑。