Skip to content

Instantly share code, notes, and snippets.

@mpilquist
Created July 16, 2011 20:05
Show Gist options
  • Save mpilquist/1086714 to your computer and use it in GitHub Desktop.
Save mpilquist/1086714 to your computer and use it in GitHub Desktop.
Treat Option as Monoid if constructed with type that is a Monoid
import scalaz._
import Scalaz._
implicit def OptionMonoid[A : Monoid]: Monoid[Option[A]] = new Monoid[Option[A]] {
def append(s1: Option[A], s2: => Option[A]) = for (x <- s1; y <- s2) yield implicitly[Monoid[A]].append(x, y)
val zero = Some(implicitly[Monoid[A]].zero)
}
val optionalNums = (1 to 10) map { some(_) }
optionalNums.asMA.sum.println
optionalNums: scala.collection.immutable.IndexedSeq[Option[Int]] = Vector(Some(1), Some(2), Some(3), Some(4), Some(5), Some(6), Some(7), Some(8), Some(9), Some(10))
Some(55)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment