我試圖在F#中將我的頭包裹在mon-,err,工作流中,同時我認爲我對基本的「Maybe」工作流有着非常紮實的理解,試圖實現一個狀態工作流程生成隨機數真的讓我難住。F#中的隨機/狀態工作流程#
我未完成的嘗試可以在這裏看到:
let randomInt state =
let random = System.Random(state)
// Generate random number and a new state as well
random.Next(0,1000), random.Next()
type RandomWF (initState) =
member this.Bind(rnd,rest) =
let value, newState = rnd initState
// How to feed "newState" into "rest"??
value |> rest
member this.Return a = a // Should I maybe feed "initState" into the computation here?
RandomWF(0) {
let! a = randomInt
let! b = randomInt
let! c = randomInt
return [a; b; c]
} |> printfn "%A"
編輯:其實得到它的工作!不完全確定它是如何工作的,所以如果任何人想把它放在一個很好的答案中,它仍然值得爭取。這是我的工作代碼:
type RandomWF (initState) =
member this.Bind(rnd,rest) =
fun state ->
let value, nextState = rnd state
rest value nextState
member this.Return a = fun _ -> a
member this.Run x = x initState
你的問題是什麼? –
如何解決它?或者一般來說應該如何構建這樣的monad /工作流程。 – monoceres
這是一個很好的描述如何狀態monad的作品。它有點冗長(3部分),但值得一讀。也許它會幫助http://fsharpforfunandprofit.com/posts/monadster/ – Petr