Skip to content

Algebra

adampingel edited this page Feb 22, 2013 · 14 revisions

This package is part of the Axle domain specific language.

The axle.algebra package contains typeclasses for algebraic structures including Functor and Monad.

The techniques used to implement these typeclasses are derived from Scalaz. A tiny fraction of Scalaz is implemented in axle.algebra -- (eventually) enough to encode examples in Learn You a Haskell in Scala.

The Spire project is a dependency of Axle. In spire.algebra you will find additional typeclasses for Monoid, Group, Ring, Field, etc.

Functor

  List(1, 2, 3).fmap(_ |+| 3)                     //> res4: List[Int] = List(4, 5, 6)
  Functor.checkIdentity(List(1, 2, 3))            //> res5: Boolean = true

  Functor.checkComposition(List(1, 2, 3), (x: Int) => x |+| 1, (y: Int) => y * 10)
                                                  //> res6: Boolean = true

Monad

  Option(4).bind(x => Some(x |+| 1))              //> res7: Option[Int] = Some(5)

  Monad.checkLeftIdentity(4, (x: Int) => Option(x |+| 1))
                                                  //> res8: Boolean = true

  Monad.checkRightIdentity(Option(4))             //> res9: Boolean = true

  Monad.checkAssociativity(Option(4), (x: Int) => Option(x |+| 1), (y: Int) => Option(y * 10))
                                                  //> res10: Boolean = true

Monoid

A singleton object, MonoidLaws, exists to prove that the Monoid laws hold on an (implicitly) given Spire Monoid.

MonoidLaws.checkLeftZero(4)                         //> res1: Boolean = true
MonoidLaws.checkRightZero(4)                        //> res2: Boolean = true
MonoidLaws.checkAssociativity(1, 2, 3)              //> res3: Boolean = true
Clone this wiki locally