Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mads-hartmann/1139775 to your computer and use it in GitHub Desktop.
Save mads-hartmann/1139775 to your computer and use it in GitHub Desktop.
Attempt to create a higher-rank polymorphic function with type bounds
/*
I want to use a higher-rank polymorphic function when transforming an AST to generalize the
'traversal' so it can be separated from the actual transformation of each node.
This snippet of code doesn't quite capture my use case but it provokes the same compile error
as I get here: https://gist.github.com/1139579
*/
trait ~>[F[_],G[_], -UpperBound] {
def apply[A <: UpperBound](a: F[A]): G[A]
}
type Id[A] = A
// Just some data so I have something to use for my type bounds
abstract class AClass { val name: String }
case class BClass(name: String, age: Int) extends AClass
case class CClass(name: String) extends AClass
// Attempt to create higher-rank polymorphic function with type bounds on the input
val transform = new (~>[Id,Id,AClass]) {
def apply[A <: AClass](a: A): A = a match {
case BClass(n,x) => BClass(n.reverse,x) // Doesn't compile: found BClass, required A
case CClass(n) => CClass(n.reverse) // Doesn't compile: found CClass, required A
}
}
def apply[B <: AClass](f: ~>[Id,Id,AClass], b: B, c: CClass): (B, CClass) = (f(b), f(c))
println(apply(transform, new BClass("Mads", 21), new CClass("runarorama")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment