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