Created
December 27, 2018 00:48
-
-
Save chemacortes/d71d59339f036bbaf451bf152f365cb5 to your computer and use it in GitHub Desktop.
An example of typeclasses with scala
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
package types | |
object Math { | |
import annotation.implicitNotFound | |
@implicitNotFound("No member of type class NumberLike in scope for ${T}") | |
trait NumberLike[T] { | |
def plus(x: T, y: T): T | |
def divide(x: T, y: Int): T | |
def minus(x: T, y: T): T | |
} | |
object NumberLike { | |
implicit object NumberLikeDouble extends NumberLike[Double] { | |
def plus(x: Double, y: Double): Double = x + y | |
def divide(x: Double, y: Int): Double = x / y | |
def minus(x: Double, y: Double): Double = x - y | |
} | |
implicit object NumberLikeInt extends NumberLike[Int] { | |
def plus(x: Int, y: Int): Int = x + y | |
def divide(x: Int, y: Int): Int = x / y | |
def minus(x: Int, y: Int): Int = x - y | |
} | |
} | |
} | |
object Statistics { | |
import Math.NumberLike | |
def mean[T](xs: Vector[T])(implicit ev: NumberLike[T]): T = | |
ev.divide(xs.reduce(ev.plus), xs.size) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment