I tried to understand the state Monad. Not as much as it is used, although it is not always easy to find. But every discussion that I find in the state Monad has basically the same information, and there is always something that I don’t understand.
Take this article for example. In it, the author has the following:
case class State[S, A](run: S => (A, S)) {
...
def flatMap[B](f: A => State[S, B]): State[S, B] =
State(s => {
val (a, t) = run(s)
f(a) run t
})
...
}
I see that types are being built correctly. However, I do not understand the second runat all.
Perhaps I am misunderstanding the purpose of this monad. I had the impression from the HaskellWiki that the state monad was like a state machine with runtransitions (although in this case the state machine really does not have fixed state transitions, such as most state machines). If so, then (a, t)one transition will be presented in the code above . The application fwill be a modification of this value and State(generation of a new State object). This leaves me completely confused as to what the second is run. It would seem that this is the second "transition". But that makes no sense to me.
, run State (A, S), , , , . , .
, ? ?
: 12/22/2015
, , . .
map:
def map[B](f: A => B): State[S, B] =
State(s => {
val (a, t) = run(s)
(f(a), t)
})
, run.
, , , run , . , -, map. flatMap run. , "" .
@Filppo, run (1, List(2,3,4,5)), (2, List(3,4,5)), . map, (Map(a->2, b->3), List(4,5)).
-, , . . ?
2nd Edit: 12/22/2015
, REPL. , .
scala> val v = State(head[Int]).flatMap { a => State(head[Int]) }
v: State[List[Int],Int] = State(<function1>
scala> v.run(List(1,2,3,4,5))
res2: (Int, List[Int]) = (2,List(3, 4, 5))
, flatMap . @Filippo, , . ?