title: State transition with `State`
body: <p>I'm trying to design state transition using <code>State</code> monad. I'm actually have a <code>java.nio.ReadableByteChannel</code> and I want to read it by fixed size chunks (e.g. 4096 bytes) and then combine some record from these chunks (e.g. by lines). </p>
  
  <p>To stay in pure FP style I defined type Chunker:</p>
  
  <pre><code>type Chunker = 
    (List[Array[Byte]], Array[Byte]) =&gt; (List[Array[Byte]], Option[Array[Byte]])
  </code></pre>
  
  <p>And now define state transition recursively using the provided chunker as follows:</p>
  
  <pre><code>def takeFirstElement(chunker: Chunker)(chunk: =&gt; Option[Array[Byte]]):
    State[List[Array[Byte]], Option[Array[Byte]]] =
    chunk match {
      case None =&gt; State.pure(None)
      case Some(ba) =&gt; scanNextChunk(chunker)(ba) flatMap {
        case None =&gt; takeFirstElement(chunker)(chunk)
        case v @ Some(a) =&gt; State.pure(v)
      }
    }
  
  def scanNextChunk(chunker: Chunker)(chunk: Array[Byte]):
    State[List[Array[Byte]], Option[Array[Byte]]] = State(chunker(_, chunk))
  </code></pre>
  
  <p>Now I wrote a simple test for it</p>
  
  <pre><code>def main(args: Array[String]): Unit = {
      val chunker: Chunker = //some complicated chunker
      val channel = //some channel
      val buf = ByteBuffer.allocate(8)
  
      val result = takeFirstElement(chunker) {
        val bytesRead = channel.read(buf)
        val data = if (bytesRead &gt;= 0) {
          val ba = new Array[Byte](bytesRead)
          System.arraycopy(buf.array(), 0, ba, 0, bytesRead)
          Some(ba)
        } else
          None
        buf.clear()
        data
      }.run(List.empty)
      println(new String(result.value._2.get))
  }
  </code></pre>
  
  <p>It works, but there are some things that are bothering me here in this example. </p>
  
  <ol>
  <li><p>Can I make use of <code>ReaderWriterStateT</code> and replace by-name parameters with defined reader. Is it possible?</p></li>
  <li><p>Is it possible to add <code>IO</code> semantic here to suspend side-effects the <code>channel</code> provides?</p></li>
  </ol>