Last active
December 17, 2015 07:28
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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