Skip to content

Instantly share code, notes, and snippets.

@markus1189
Created May 18, 2013 09:00
Show Gist options
  • Save markus1189/5603788 to your computer and use it in GitHub Desktop.
Save markus1189/5603788 to your computer and use it in GitHub Desktop.
object Reader {
def pure[C,A](a: A): Reader[C,A] = (_: C) => a
def sequence[C,A](rs: List[Reader[C,A]]): Reader[C,List[A]] = (c: C) =>
rs.foldLeft(List[A]()) { (accu,reader) => accu :+ reader(c) }
def filter[C,A](xs: List[A])(p: A => Reader[C,Boolean]): Reader[C,List[A]] = (c: C) => {
val bs: List[Reader[C,Boolean]] = xs.map(p)
xs.foldLeft(List[A]()) { (accu,x) => if (p(x)(c)) accu :+ x else accu }
}
implicit def reader[A,B]: (A => B) => Reader[A,B] = (f: A => B) => Reader(f)
}
case class Reader[C,A](g: C => A) {
def apply(c: C) = g(c)
def foreach: (A => Unit) => Reader[C,Unit] = map[Unit]
def map[B](f: A => B): Reader[C,B] = (c: C) => f(g(c))
def flatMap[B](f: A => Reader[C,B]): Reader[C,B] = (c: C) => f(g(c))(c)
def &&&[B](that: Reader[C,B]) : Reader[C,(A,B)] = (c: C) => (this(c),that(c))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment