【发布时间】:2015-10-17 02:54:06
【问题描述】:
PartialFunction 是一个自然提取器,它的lift 方法提供了精确的提取器功能。所以使用部分函数作为提取器会非常方便。这将允许以比 PartialFunction 可用的普通 orElse 更复杂的方式组合模式匹配表达式
所以我尝试使用皮条客我的图书馆方法并失败了
这里更新:正如@Archeg 所示,还有另一种有效的转换方法。所以我将它包含在提供的代码中。
我也尝试了一些更复杂的解决方案,但都失败了
object Test {
class UnapplyPartial[-R, +T](val fun : PartialFunction[R,T]) {
def unapply(source : R) : Option[T] = fun.lift(source)
}
implicit def toUnapply[R,T](fun : PartialFunction[R,T]) : UnapplyPartial[R,T] = new UnapplyPartial(fun)
class PartialFunOps[-R, +T](val fun : PartialFunction[R,T]) {
def u : UnapplyPartial[R, T] = new UnapplyPartial(fun)
}
implicit def toPartFunOps[R,T](fun : PartialFunction[R,T]) : PartialFunOps[R,T] = new PartialFunOps(fun)
val f : PartialFunction[String, Int] = {
case "bingo" => 0
}
val u = toUnapply(f)
def g(compare : String) : PartialFunction[String, Int] = {
case `compare` => 0
}
// error while trying to use implicit conversion
def testF(x : String) : Unit = x match {
case f(i) => println(i)
case _ => println("nothing")
}
// external explicit conversion is Ok
def testU(x : String) : Unit = x match {
case u(i) => println(i)
case _ => println("nothing")
}
// embedded explicit conversion fails
def testA(x : String) : Unit = x match {
case toUnapply(f)(i) => println(i)
case _ => println("nothing")
}
// implicit explicit conversion is Ok
def testI(x : String) : Unit = x match {
case f.u(i) => println(i)
case _ => println("nothing")
}
// nested case sentences fails
def testInplace(x : String) : Unit = x match {
case { case "bingo" => 0 }.u(i) => println(i)
case _ => println("nothing")
}
// build on the fly fails
def testGen(x : String) : Unit = x match {
case g("bingo").u(i) => println(i)
case _ => println("nothing")
}
// implicit conversion without case is also Ok
def testFA(x : String) : Option[Int] =
f.unapply(x)
}
我收到以下错误消息:
UnapplyImplicitly.scala:16: 错误:值 f 不是案例类,也没有 unapply/unapplySeq 成员 案例 f(i) => println(i)
UnapplyImplicitly.scala:28: 错误:'=>' 预期但 '(' 找到。 case toUnapply(f)(i) => println(i)
使用TestI 所示的假定形式可以避免此错误。但我很好奇是否可以避免testInplace 错误:
UnapplyImplicitly.scala:46: 错误:简单模式的非法开始 案例 { 案例“宾果” => 0 }.u(i) => println(i) ^
UnapplyImplicitly.scala:47: 错误:'=>' 预期但 ';'成立。 case _ => println("nothing")
UnapplyImplicitly.scala:56: 错误:'=>' 预期但 '.'成立。 案例 g("bingo").u(i) => println(i) ^
【问题讨论】:
标签: scala pattern-matching implicit-conversion