Skip to content

Instantly share code, notes, and snippets.

@hamishdickson
Created January 10, 2017 14:00
Show Gist options
  • Save hamishdickson/3fd7114e6f31499d66bdee1ec3442205 to your computer and use it in GitHub Desktop.
Save hamishdickson/3fd7114e6f31499d66bdee1ec3442205 to your computer and use it in GitHub Desktop.
Playing with tagged types and type classes in scala
[info] Loading global plugins from /Users/hamishdickson/.sbt/0.13/plugins
[info] Updating {file:/Users/hamishdickson/.sbt/0.13/plugins/}global-plugins...
[info] Resolving org.fusesource.jansi#jansi;1.4 ...
[info] Done updating.
[info] Set current project to catsSandbox (in build file:/Users/hamishdickson/Workspace/catsSandbox/)
[info] Starting scala interpreter...
[info]
Welcome to Scala 2.12.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_101).
Type in expressions for evaluation. Or try :help.
scala> import shapeless._
import shapeless._
scala> import shapeless.tag._
import shapeless.tag._
scala> trait Foo
defined trait Foo
scala> trait Magma[T] {
| def combine(a: T, b: T): T
| }
defined trait Magma
scala> implicit val intMagma = new Magma[Int] {
| def combine(a: Int, b: Int): Int = a + b
| }
intMagma: Magma[Int] = $anon$1@445f3db0
scala> implicit val fooMagma = new Magma[Int @@ Foo] {
| def combine(a: Int @@ Foo, b: Int @@ Foo): Int @@ Foo = a * b
| }
<console>:21: error: type mismatch;
found : Int
required: shapeless.tag.@@[Int,Foo]
(which expands to) Int with shapeless.tag.Tagged[Foo]
Note: implicit value fooMagma is not applicable here because it comes after the application point and it lacks an explicit result type
def combine(a: Int @@ Foo, b: Int @@ Foo): Int @@ Foo = a * b
^
scala> implicit val fooMagma = new Magma[Int @@ Foo] {
| def combine(a: Int @@ Foo, b: Int @@ Foo): Int @@ Foo = tag[Foo](a * b)
| }
fooMagma: Magma[shapeless.tag.@@[Int,Foo]] = $anon$1@5ab00fe9
scala> implicitly[Magma[Int @@ Foo]]
res0: Magma[shapeless.tag.@@[Int,Foo]] = $anon$1@5ab00fe9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment