Skip to content

Instantly share code, notes, and snippets.

@fikovnik
Created March 2, 2018 13:32
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 fikovnik/fcc54e2b869bc79ed7341fe2b62f0363 to your computer and use it in GitHub Desktop.
Save fikovnik/fcc54e2b869bc79ed7341fe2b62f0363 to your computer and use it in GitHub Desktop.
Simple matcher for Scala
object MatchExample extends App {
trait Matcher[-T] extends (T => Boolean)
def matches[A](x: A, m: Matcher[A]) = m(x)
trait F[-C[_]] {
def contains[A >: B, B](c: C[A], x: B): Boolean
}
implicit object OptionF extends F[Option] {
override def contains[A >: B, B](c: Option[A], x: B): Boolean = c.contains(x)
}
implicit object IterableF extends F[Iterable] {
override def contains[A >: B, B](c: Iterable[A], x: B): Boolean = c.exists(_ == x)
}
def contains[A, B[A]](y: A)(implicit f: F[B]): Matcher[B[A]] = new Matcher[B[A]] {
override def apply(v1: B[A]): Boolean = f.contains(v1, y)
}
class X { def x = 1 }
class Y extends X { def y = 2 }
val x1 = new X
val y1 = new Y
val lx: List[X] = x1 :: y1 :: Nil
val ly: List[Y] = y1 :: Nil
// println(matches(Option(x1), contains(x1)))
// println(matches(lx, contains(x1)))
// println(matches(lx, contains(y1)))
// Error:(93, 39) ambiguous implicit values:
// both object OptionF in object MatchExample of type MatchExample.OptionF.type
// and object IterableF in object MatchExample of type MatchExample.IterableF.type
// match expected type MatchExample.F[B]
// println(matches(Option(x1), contains(x1)))
implicit class Mather2Any[A](that:A) {
def matches(m: Matcher[A]): Boolean = m(that)
}
println(Option(x1) matches contains(x1))
println(lx matches contains(x1))
println(lx matches contains(y1))
println(Map(1->2) matches contains(1->2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment