I'm studying Michael Pilquist's excellent state monad lecture here. I get stuck at 54 min with two questions.
If
ofsis anOption[FollowerStats], what is the?operator? I can't find a ternary operator on Option in Scala 2.10.2How does the last generator put an updated cache (with hit or miss incremented) back into the
Stateresult of the checkCache method? The returnedStateseems to be be discarded and the for comprehension seems to only yielding theOption[FollowerStats]
.
def checkCache(u: String): State[Cache, Option[FollowerState]] = for {
c <- State.get[Cache]
ofs <- State.state {
c.get(u).collect {
case Timestamped(fs, ts) if !state(ts) => fs
}
}
_ <- State.put(ofs ? c.recordHit | c.recordMiss)
} yield ofs
To try and understand I attempted to re-write the for comprehension, but it's not helped.
State.get[Cache].flatMap{ c =>
State.state{c.get(u).collect(...)}.flatMap{ ofs =>
State.put(ofs ? c.recordHit | c.recordMiss).map{ _ =>
ofs
}
}
}
Update:
I think I've grasped the key to point 2 thanks to the answers. I didn't realise that that the yield is essentially saying: take the last state s => (s,()) from the put and replace the Unit value type with ofs, to get s =>(s,ofs). I guess the key is realising that the yield isn't literally returning ofs, but it's translated as State.map.
Update Understand the option bit now. I guess the presentation still uses the implicits from Scalaz although it's deriving the state monad.
Option ? ... | ...bit comes from an implicit conversion (specifically an implicit classOptionOps). You have probably already dealt with implicit conversions such as being able to calltoInton a String due to an implicit conversion toStringOps- this is much the same. - Shadowlands