Skip to content

Instantly share code, notes, and snippets.

@channingwalton
Created March 7, 2014 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save channingwalton/9416357 to your computer and use it in GitHub Desktop.
Save channingwalton/9416357 to your computer and use it in GitHub Desktop.
Turning nulls into zeroes, zeroes into empties
object MonoidHomomorphism extends App {
import scalaz._
import Scalaz._
/**
* Turn any null into the Zero value for its type
*/
def nullAsZero[T: Monoid : Equal](a: T) = if (a == null) implicitly[Monoid[T]].zero else a
/**
* turn a Zero value of A into an empty M, or put a into an M
*/
def zeroToEmpty[A : Equal: Monoid, M[_] : Applicative : PlusEmpty](a: A): M[A] =
if (a.isMZero) PlusEmpty[M].empty else Applicative[M].point(a)
/**
* Turn null of T into empty M, or put a into M
*/
def nullToEmpty[T: Monoid : Equal, M[_] : Applicative : PlusEmpty](a: T) = zeroToEmpty[T, M](nullAsZero(a))
println(zeroToEmpty[String, Option]("")) // None
println(zeroToEmpty[String, Option]("a")) // Some("a")
val v: String = null
println(nullToEmpty[String, Option](v)) // None
println(zeroToEmpty[Int, List](0)) // Nil
println(zeroToEmpty[Int, List](1)) // List(1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment