Discord is now Scala’s main chat platform. Please join us at https://discord.com/invite/scala
Hello, I'm going through the Functional Programming in Scala and on the chapter about State we have:case class State[S, +A](run: S => (A, S))
then we have a methoddef simulateMachine(inputs: List[Input]): State[Machine, (Int, Int)]
later on:
val m: Machine = Machine(true, 5, 10)
Candy.simulateMachine(inputs).run(m)
What is making me confused is that "m" is of type machine and "run" expects a "S => (A, S)" function... so how could I pass Machine to "run"?
State[Machine, *]
so run
takes S
which is Machine
.run
, you access that field
()
, you call Function.apply
(under the hood) therefore passing the S
to the function
S
type parameter in this case is equal to Machine
, which is why you can pass a Machine
to the function
Candy.simulateMachine(inputs).run.apply(m) // we are calling the apply method on the run value which is an instance of the function class
S => (A, S)
Function.
when you create an State you have to pass a Function.
I think this view is confusing
but where is the definition of run where it takes the S and
so you have various State
computations, right?
map
and flatMap
and pure
etc
State
computation, i.e get
and put
I think this view is confusing
so actually I take this back
State
computation by passing the function
get
and put
are built
State
represents is a sequence of transformations over an S
State[S, A]
means, "a sequence of transformation over an S
, which will result in an A
"
mySequenceOfTransformationsWhichIsStateSA.run(initialState)
this is what you do when you write
mySequenceOfTransformationsWhichIsStateSA.run(initialState)
perfect :)
get
, and its type is State[S, S]
, i.e. the sequence of transformations on S
which will return S
itself (which is what "getting the state" is)