Created
August 11, 2011 14:26
-
-
Save mads-hartmann/1139775 to your computer and use it in GitHub Desktop.
Attempt to create a higher-rank polymorphic function with type bounds
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
/* | |
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