Slide 19
Slide 19 text
Now let’s implement flatMap. case class State[S, A](run: S => (S, A)) {
def map[B](f: A => B): State[S, B] =
State { s =>
val (s1, a) = run(s)
(s1, f(a))
}
def flatMap[B](g: A => State[S, B]): State[S, B] = ???
}
def flatMap[B](f:A=>State[S,B]):State[S,B] =
State { s =>
val (s1,a) = run(s)
f(a).run(s1)
}
the instance’s run function returns an S and a B we can get an S and a B if we have a State[S,B] simplify
If we have an A then we can get a State[S,B] by calling f We can get an A by calling our own run function inline state and use s1 in second call to run
def flatMap[B](f:A=>State[S,B]):State[S,B] =
State { s =>
val (s1,a) = run(s)
val state: State[S, B] = f(a)
state.run(s)
}
def flatMap[B](f:A=>State[S,B]):State[S,B] =
State { s =>
???
}
flatMap returns a new State monad instance
def flatMap[B](f:A=>State[S,B]):State[S,B] =
State { s =>
val s1 = ???
val b = ???
(s1,b)
}
def flatMap[B](f:A=>State[S,B]):State[S,B] =
State { s =>
val state: State[S, B] = ???
val result = state.run(s)
val s1 = result._1
val b = result._2
(s1, b)
}
def flatMap[B](f:A=>State[S,B]):State[S,B] =
State { s =>
val state: State[S, B] = ???
state.run(s)
}
def flatMap[B](f:A=>State[S,B]):State[S,B] =
State { s =>
val a = ???
val state: State[S, B] = f(a)
state.run(s)
}
1
2 4
5 6 7
3
@philip_schwarz