Created
November 24, 2011 15:21
-
-
Save mads-hartmann/1391572 to your computer and use it in GitHub Desktop.
Simple Example from "Fun with type functions" in Scala
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
/* | |
Simple Example from "Fun with type functions" | |
class Add a b where | |
type SumTy a b | |
add :: a -> b -> SumTy a b | |
instance Add Integer Double where | |
type SumTy Integer Double = Double | |
add x y = fromIntegral x + y | |
instance Add Double Integer where | |
type SumTy Double Integer = Double | |
add x y = x + fromIntegral y | |
instance (Num a) => Add a a where | |
type SumTy a a = a | |
add x y = x + y | |
*/ | |
trait Add[A,B] { | |
type SumTy[A,B] | |
def add(a: A, b: B): SumTy[A,B] | |
} | |
implicit object AddIntDouble extends Add[Int, Double] { | |
type SumTy[Int, Double] = Double | |
def add(a: Int, b: Double) = a.toDouble + b | |
} | |
implicit object AddDOubleInteger extends Add[Double, Int] { | |
type SumTy[Double, Int] = Double | |
def add(a: Double, b: Int) = a + b.toDouble | |
} | |
// implicit object AddNumeric extends Add[Numeric[_], Numeric[_]] { | |
// type SumTy[???, ???] = Numeric[_] // I want to ensure that A and B are Numeric[_] | |
// def add(a: Numeric[_], b: Numeric[_]) = a plus b | |
// } | |
// Doesn't compile currently: illegal dependent method type | |
def addSomething[A,B](a: A, b: B)(implicit addTC: Add[A,B]): addTC.SumTy[A,B] = | |
addTC.add(a,b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment