Created
December 24, 2011 10:19
-
-
Save piotrga/1517067 to your computer and use it in GitHub Desktop.
Type classes 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
trait TypeClass1[T]{ | |
def add(a:T, b:T) : T | |
} | |
implicit val ints = new TypeClass1[Int]{ | |
def add(a: Int, b: Int) = a+b | |
} | |
def sum[T: TypeClass1](list: List[T]) = { | |
require(!list.isEmpty) | |
val typeClass = implicitly[TypeClass1[T]] | |
list.reduce(typeClass.add(_,_)) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment