Created
March 26, 2011 08:03
-
-
Save jesperdj/888123 to your computer and use it in GitHub Desktop.
Type classes for a generic interpolate method
This file contains 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
// See: http://www.scala-notes.org/2010/08/a-generic-interpolate-method-using-type-classes/ | |
// Trait for types that can be multiplied with a T, resulting in an R | |
trait Multipliable[-T, +R] { | |
def *(value: T): R | |
} | |
// Trait for types to which a T can be added, resulting in an R | |
trait Addable[-T, +R] { | |
def +(value: T): R | |
} | |
trait MultipliableSame[T] extends Multipliable[T, T] | |
trait AddableSame[T] extends Addable[T, T] | |
trait Interpolatable[T] extends Multipliable[Double, T] with AddableSame[T] | |
// Linearly interpolate between two values | |
def interpolate[@specialized(Double) T <% Interpolatable[T]](t: Double, a: T, b: T): T = a * (1.0 - t) + b * t | |
// Make Double interpolatable | |
implicit def doubleToInterpolatable(n: Double) = new Interpolatable[Double] { | |
def *(value: Double): Double = n * value | |
def +(value: Double): Double = n + value | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment