title: Scala state monad in for comprehension
body: <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>