Skip to content

Instantly share code, notes, and snippets.

@tonymorris
Last active December 17, 2015 07:28
Show Gist options
  • Save tonymorris/5572544 to your computer and use it in GitHub Desktop.
Save tonymorris/5572544 to your computer and use it in GitHub Desktop.
The `scala.List` and `scala.Option` data types would benefit from the addition of `coflatMap` and `coflatten` methods.
case class OptionAdd[+A](o: Option[A]) {
// Can be defined in terms of coflatten.
def coflatMap[B](f: Option[A] => B): Option[B] =
// o map (_ => f(o))
o match {
case None => None
case Some(_) => Some(f(o))
}
def coflatten: Option[Option[A]] =
coflatMap(identity)
}
case class ListAdd[+A](l: List[A]) {
def coflatMap[B](f: List[A] => B): List[B] =
coflatten map f
// Can be defined in terms of coflatMap.
def coflatten: List[List[A]] =
l match {
case Nil => Nil
case _::t => l :: ListAdd(t).coflatten
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment