Skip to content

Instantly share code, notes, and snippets.

@js1972
Created August 16, 2014 08:22
Show Gist options
  • Save js1972/19e367a039022e9d8f65 to your computer and use it in GitHub Desktop.
Save js1972/19e367a039022e9d8f65 to your computer and use it in GitHub Desktop.
Monoid implementation for Double. From ScalaZ 7.1 Double and Float are no longer supported as they don't totally fulfill the Monoid laws.
package com.example
import scalaz._
import Scalaz._
object testing {
1 |+| 1 //> res0: Int = 2
//ScalaZ no longer supports a Monoid of Double or Float as they don't
//pass the monoid laws as per https://github.com/scalaz/scalaz/issues/334.
// Here's my own:
implicit val doubleInstance: Monoid[Double] = new Monoid[Double] {
def append(f1: Double, f2: => Double) = f1 + f2
def zero: Double = 0d
} //> doubleInstance : scalaz.Monoid[Double] = com.example.testing$$anonfun$main$
//| 1$$anon$1@7aa34f04
import Tags.{Multiplication}
implicit val doubleMultiplicationNewType: Semigroup[Double @@ Multiplication] = new Semigroup[Double @@ Multiplication] {
def append(f1: Double @@ Multiplication, f2: => Double @@ Multiplication) = Multiplication(Tag.unwrap(f1) * Tag.unwrap(f2))
def zero: Double @@ Multiplication = Multiplication(1.0d)
} //> doubleMultiplicationNewType : scalaz.Semigroup[scalaz.@@[Double,scalaz.Tags
//| .Multiplication]] = com.example.testing$$anonfun$main$1$$anon$2@75846058
2.0 |+| 3.5 //> res1: Double = 5.5
Multiplication(2.0) |+| Multiplication(3.5) //> res2: scalaz.@@[Double,scalaz.Tags.Multiplication] = 7.0
//List(true, true, false, true) foldMap { _. }
case class Blah(security: String, price: Double)
val myList = List(Blah("a", 2.0), Blah("b", 4.0))
//> myList : List[com.example.testing.Blah] = List(Blah(a,2.0), Blah(b,4.0))
//myList.foldMap(Tags.Monoidal(_.price))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment