Skip to content

Instantly share code, notes, and snippets.

@landonf
Created October 14, 2014 20:20
Show Gist options
  • Save landonf/f543d8a1b60e5674c15e to your computer and use it in GitHub Desktop.
Save landonf/f543d8a1b60e5674c15e to your computer and use it in GitHub Desktop.
Automatic boxing and unboxing of an instance that conforms to a typeclass, and the typeclass itself.
object example {
import scala.language.higherKinds
object @@ {
case class TypeClassManifest[V, T[_]](value: V)(implicit val typeClass: T[V])
def apply[V, T[_]](instance: V)(implicit T: T[V]) = TypeClassManifest(instance)
implicit def typeClass[V, T[_]] (manifest: TypeClassManifest[V, T]): T[V] = manifest.typeClass
implicit def typeInstance[V, T[_]] (manifest: TypeClassManifest[V, T]): V = manifest.value
}
type @@[V, T[_]] = @@.TypeClassManifest[V, T]
// Example usage:
def numericList[T : Numeric] (list: List[T]): List[T @@ Numeric] = {
list.map(@@(_))
}
def adder[T : Numeric] (x: T, y: T): T = implicitly[Numeric[T]].plus(x, y)
numericList(List(1, 2, 3)).foldLeft(0)(adder(_, _))
}
@landonf
Copy link
Author

landonf commented Oct 14, 2014

scala> example.numericList(List(1, 2, 3)).foldLeft(0)(adder(_, _))
res3: Int = 6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment