Skip to content

Instantly share code, notes, and snippets.

@juanjovazquez
Created May 26, 2020 12:26
Show Gist options
  • Save juanjovazquez/8176798a22fb28e9fbedb1bf8eb2aa04 to your computer and use it in GitHub Desktop.
Save juanjovazquez/8176798a22fb28e9fbedb1bf8eb2aa04 to your computer and use it in GitHub Desktop.
Errors using context bounded poly functions in Scala 3
package polyMap
type Id[T] = T
trait Negation[A]:
def neg(a: A): A
object Negation:
def apply[A](using ev: Negation[A]): Negation[A] = ev
given Negation[Int] = (a: Int) => -a
given Negation[String] = (x: String) => s"no-$x"
given Negation[Boolean] = (x: Boolean) => !x
@main def PolyMapApp(): Unit =
val t = (10, "foo", true)
// 0. context bound -> syntax not allowed
//val r = t.map[Id]([T: Negation] => (x: T) => Negation[T].neg(x))
// error: ']' expected, but ':' found
// 1. anonymous context parameter -> syntax error!
//val r = t.map[Id]([T] => (x: T) => (using Negation[T]) => Negation[T].neg(x))
// error: ')' expected, but '[' found
// 2. named context parameter -> compilation error!
//val r = t.map[Id]([T] => (x: T) => (using negation: Negation[T]) => negation.neg(x))
//Found: Object with PolyFunction {...}
//Required: PolyFunction{apply: [t](x$1: t): polyMap.Id[t]}
// 3. context function type -> no compilation error but tuple of lambdas as result.
// It seems the compiler is not providing the context parameter implicitly
type Negate[A] = Negation[A] ?=> A
val r = t.map[Negate]([T] => (x: T) => (using negation: Negation[T]) => negation.neg(x))
println(r)
// (Lambda$10139/824777939@371ca907,Lambda$10139/824777939@1cb498e1,Lambda$10139/824777939@51362999)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment