Note that there are some explanatory texts on larger screens.

plurals
  1. POScala state monad in for comprehension
    primarykey
    data
    text
    <p>I'm studying Michael Pilquist's excellent state monad lecture <a href="http://www.youtube.com/watch?v=Jg3Uv_YWJqI" rel="nofollow">here</a>. I get stuck at 54 min with two questions.</p> <ol> <li><p>If <code>ofs</code> is an <code>Option[FollowerStats]</code>, what is the <code>?</code> operator? I can't find a ternary operator on Option in Scala 2.10.2</p></li> <li><p>How does the last generator put an updated cache (with hit or miss incremented) back into the <code>State</code> result of the checkCache method? The returned <code>State</code> seems to be be discarded and the for comprehension seems to only yielding the <code>Option[FollowerStats]</code></p></li> </ol> <p>.</p> <pre><code>def checkCache(u: String): State[Cache, Option[FollowerState]] = for { c &lt;- State.get[Cache] ofs &lt;- State.state { c.get(u).collect { case Timestamped(fs, ts) if !state(ts) =&gt; fs } } _ &lt;- State.put(ofs ? c.recordHit | c.recordMiss) } yield ofs </code></pre> <p>To try and understand I attempted to re-write the for comprehension, but it's not helped.</p> <pre><code>State.get[Cache].flatMap{ c =&gt; State.state{c.get(u).collect(...)}.flatMap{ ofs =&gt; State.put(ofs ? c.recordHit | c.recordMiss).map{ _ =&gt; ofs } } } </code></pre> <p><strong>Update:</strong> 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 <code>s =&gt; (s,())</code> from the <code>put</code> and replace the <code>Unit</code> value type with ofs, to get <code>s =&gt;(s,ofs)</code>. I guess the key is realising that the yield isn't literally returning ofs, but it's translated as State.map.</p> <p><strong>Update</strong> Understand the option bit now. I guess the presentation still uses the implicits from Scalaz although it's deriving the state monad.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload