Skip to content

Instantly share code, notes, and snippets.

@globulon
Created March 4, 2012 21:01
Show Gist options
  • Select an option

  • Save globulon/1974768 to your computer and use it in GitHub Desktop.

Select an option

Save globulon/1974768 to your computer and use it in GitHub Desktop.
Collect
def toCollector[A, B, U](x: A, f: (A) ⇒ B, g: U ⇒ U) = State[B,U]((s: U) ⇒ (f(x), g(s)))
def collect[A, B, T[_], U](source: T[A])(f: (A) ⇒ B, g: U ⇒ U)(implicit t: Traverse[T]): State[T[B], U] = {
type Projection[X] = State[X, U]
implicit val A = stateApplicative[U]()
t.traverse[Projection, A, B](source)((x: A) ⇒ toCollector(x, f, g))
}
println((collect(List(10, 20, 30, 40))((a: Int) ⇒ 2 * a, (i: Int) ⇒ i + 1)).apply(0))
//Produces (List(20, 40, 60, 80),4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment