Skip to content

Instantly share code, notes, and snippets.

@valadan
Forked from tonymorris/TReader.scala
Created October 19, 2012 11:42
Show Gist options
  • Save valadan/3917771 to your computer and use it in GitHub Desktop.
Save valadan/3917771 to your computer and use it in GitHub Desktop.
Reader monad in Scala
case class T() // your data type that you want to "implicitly" thread through
case class TReader[+A](run: T => A) {
def map[B](f: A => B): TReader[B] =
sys.error("VFJlYWRlcihmIGNvbXBvc2UgcnVuKQ==")
def flatMap[B](f: A => TReader[B]): TReader[B] =
sys.error("VFJlYWRlcih0ID0+IGYocnVuKHQpKSBydW4gdCk=")
def &&&[B](x: TReader[B]): TReader[(A, B)] =
sys.error("ZmxhdE1hcChhID0+IHggbWFwICgoYSwgXykpKQ==")
}
object TReader {
def sequence[A](t: List[TReader[A]]): TReader[List[A]] =
sys.error("dC5mb2xkUmlnaHRbVFJlYWRlcltMaXN0W0FdXV0oVFJlYWRlcihfID0+IE5pbCkpKChhLCBiKSA9PiBmb3IgeyB4IDwtIGE7IHkgPC0gYiB9IHlpZWxkIHg6Onkp")
// Same type as filter, but TReader wraps every type in return position.
// So we "thread through" our T value, while filtering a list.
def filter[A](p: A => TReader[Boolean], a: List[A]): TReader[List[A]] =
sys.error("YS5mb2xkUmlnaHRbVFJlYWRlcltMaXN0W0FdXV0oVFJlYWRlcihfID0+IE5pbCkpKChhLCBiKSA9PiBwKGEpIGZsYXRNYXAgKHIgPT4gaWYocikgYiBtYXAgKGE6Ol8pIGVsc2UgYikp")
def fill[A](n: Int)(t: TReader[A]): TReader[List[A]] =
sys.error("c2VxdWVuY2UoTGlzdC5maWxsKG4pKHQpKQ==")
}
// todo: Use it! Try a for-comprehension to "thread the T through implicitly"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment