Skip to content

Instantly share code, notes, and snippets.

@danslapman
Created July 10, 2018 20:15
Show Gist options
  • Save danslapman/dbfc664794b951013bcb5c00a06cd511 to your computer and use it in GitHub Desktop.
Save danslapman/dbfc664794b951013bcb5c00a06cd511 to your computer and use it in GitHub Desktop.
Combine partial functions of different types
import scala.reflect.runtime.universe._
type ¬[A] = A => Nothing
type ∨[T, U] = ¬[¬[T] with ¬[U]]
type ¬¬[A] = ¬[¬[A]]
type |∨|[T, U] = { type λ[X] = ¬¬[X] <:< (T ∨ U) }
val intpf: PartialFunction[Int, Int] = { case i: Int => i }
val strpf: PartialFunction[String, String] = { case str: String => str }
def applyOne[T1: TypeTag, T2: TypeTag, T: (T1 |∨| T2)#λ : TypeTag](f1: PartialFunction[T1, T1], f2: PartialFunction[T2, T2])(arg: T): T = {
typeOf[T] match {
case t if t =:= typeOf[T1] => f1(arg.asInstanceOf[T1]).asInstanceOf[T]
case t if t =:= typeOf[T2] => f2(arg.asInstanceOf[T2]).asInstanceOf[T]
}
}
val res = applyOne(intpf, strpf)(1)
println(res)
println(applyOne(intpf, strpf)("test"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment