Skip to content

Instantly share code, notes, and snippets.

@stew
Created April 5, 2012 11:33
Show Gist options
  • Save stew/2310098 to your computer and use it in GitHub Desktop.
Save stew/2310098 to your computer and use it in GitHub Desktop.
use state + traverse
scala> import scalaz._
import scalaz._
scala> import Scalaz._
import Scalaz._
scala> case class FooState(partialResult: List[Int], result: List[List[Int]]) {
| def newPartial(n:Int) = FooState(n::partialResult, result)
| def newResult = FooState(List(), partialResult.reverse :: result)
| }
defined class FooState
scala> def nextFooState(n: Option[Int]) = modify( (s:FooState) => n match {
| case None => s.newResult
| case Some(nn) => s.newPartial(nn)
| })
nextFooState: (n: Option[Int])scalaz.package.State[FooState,FooState]
scala> def chunks(l: List[Option[Int]]) : List[List[Int]] = {
| val initialState = FooState(List(),List())
| val finalState = l.traverseS(nextFooState).exec(initialState).newResult
| finalState.result.reverse
| }
chunks: (l: List[Option[Int]])List[List[Int]]
scala> chunks(List(Some(1), Some(2), None, Some(3), Some(4), Some(5), None, Some(6),Some(7)))
res0: List[List[Int]] = List(List(1, 2), List(3, 4, 5), List(6, 7))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment