0

我尝试在 Scala 中创建一个小型匹配库。我有以下类型表示一个匹配器,它代表一个类型的约束T

trait Matcher[-T] extends (T => Boolean)

以及一个matches检查该约束是否适用于给定实例的函数:

def matches[A](x: A, m: Matcher[A]) = m(x)

有了这个,我希望能够编写如下检查:

matches(Option(1), contains(1))
matches(Seq(1,2), contains(1))

可以在任何容器contains进行抽象。我使用类型类尝试了以下抽象:

trait F[-C[_]] {
  def contains[A >: B, B](c: C[A], x: B): Boolean 
}

然后我可以用它来定义contains函数:

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)
}

有两个隐式定义,一个用于Option

implicit object OptionF extends F[Option] {
  override def contains[A >: B, B](c: Option[A], x: B): Boolean = c.contains(x)
}

Iterable

implicit object IterableF extends F[Iterable] {
  override def contains[A >: B, B](c: Iterable[A], x: B): Boolean = c.exists(_ == x)
}

但是,当我每次调用matches. 他们都是一样的:

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]
matches(Option(1), contains(1))

似乎类型推断无法正确推断类型,这就是两个隐式匹配的原因。

如何matches定义函数没有歧义?

我还尝试使用隐式转换将matches函数直接添加到任何类型:

implicit class Mather2Any[A](that:A) {
  def matches(m: Matcher[A]): Boolean = m(that)
}

这工作得很好:

Option(x1) matches contains(x1)
lx matches contains(x1)
lx matches contains(y1)

我不明白为什么matches方法不起作用时功能不起作用?看起来问题在于推理仅基于返回类型。例如,不是contains我可以isEmpty使用 not 参数,它再次适用于matches方法但不适用于函数。

完整的代码清单在这个gist中。

4

1 回答 1

0

What you need is to split the parameters into two lists:

def matches[A](x: A)(m: Matcher[A]) = m(x)

matches(Option(1))(contains(1))
matches(Seq(1,2))(contains(1))

A gets inferred from x and is then available while type-checking m. With Mather2Any you have the same situation.

Side note: variations on this get asked often, I just find it faster to reply than to find a duplicate.

于 2018-03-02T14:24:51.473 回答