Created
March 7, 2014 17:52
-
-
Save channingwalton/9416357 to your computer and use it in GitHub Desktop.
Turning nulls into zeroes, zeroes into empties
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
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