Skip to content

Instantly share code, notes, and snippets.

@vendethiel
Last active February 21, 2024 10:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vendethiel/a900db5036f8e00e12d5cfbc13ed4977 to your computer and use it in GitHub Desktop.
Save vendethiel/a900db5036f8e00e12d5cfbc13ed4977 to your computer and use it in GitHub Desktop.
sealed trait Type {}
case class BuiltinType(t: String) extends Type {
override def toString = t
}
case class UnknownType(name: String) extends Type {
override def toString = name
}
case class FunctionType(from: Type, to: Type) extends Type {
override def toString: String = {
val fromS = from.toString
(if (fromS.contains("->")) s"($fromS)" else fromS) + " -> " + to
}
}
case class HKT1(name: String, subtype: Type) extends Type {
override def toString: String = {
val subtypeS = subtype.toString
name + " " + (if (subtypeS.contains("->")) s"($subtypeS)" else subtypeS)
}
}
val Boolean = BuiltinType("Boolean")
val Int = BuiltinType("Int")
def matches(t1: Type, t2: Type): Boolean = (t1, t2) match {
case (UnknownType(_), _) => true
case (_, UnknownType(_)) => true
case (HKT1(_, a), HKT1(_, b)) => matches(a, b)
case (BuiltinType(a), BuiltinType(b)) => a == b
case (FunctionType(fromA, toA), FunctionType(fromB, toB)) => matches(fromA, fromB) && matches(toA, toB)
case _ => false
}
val signatures: Seq[FunctionType] = Seq(
// FunctionType(Boolean, Int),
// FunctionType(Int, Boolean),
// FunctionType(UnknownType("a"), UnknownType("b")),
// FunctionType(UnknownType("a"), Int),
// FunctionType(HKT1("m", UnknownType("a")), Int),
// FunctionType(FunctionType(UnknownType("a"), UnknownType("b")), FunctionType(UnknownType("a"), FunctionType(Int, Int))),
FunctionType(HKT1("m", UnknownType("a")), FunctionType(FunctionType(UnknownType("a"), HKT1("m", UnknownType("b"))), HKT1("m", UnknownType("a")))),
FunctionType(HKT1("m", UnknownType("a")), FunctionType(HKT1("m", UnknownType("b")), HKT1("m", UnknownType("a"))))
)
println("Defined functions:")
signatures.foreach(s => println(" - " + s))
def printMatches(lookingFor: Type): Unit = {
val matching = signatures.filter(matches(lookingFor, _))
println(s"${matching.length} matching for $lookingFor:")
matching.foreach(s => println(" - " + s))
}
printMatches(FunctionType(UnknownType("a"), UnknownType("b")))
printMatches(FunctionType(UnknownType("a"), UnknownType("m b")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment