And*_*huk 6 scala pattern-matching human-readable
是否有可能以某种方式将PartialFunction(让我们假设它总是只包含一个案例)编组成人类可读的东西?
假设我们有类型Any(messages:List [Any])的集合和使用模式匹配块定义的PartialFuntion [Any,T]的数量.
case object R1
case object R2
case object R3
val pm1: PartialFunction[Any, Any] = {
case "foo" => R1
}
val pm2: PartialFunction[Any, Any] = {
case x: Int if x > 10 => R2
}
val pm3: PartialFunction[Any, Any] = {
case x: Boolean => R3
}
val messages: List[Any] = List("foo", 20)
val functions = List(pm1, pm2)
Run Code Online (Sandbox Code Playgroud)
然后我们可以找到所提供的PF和相关应用程序匹配的所有消息
val found: List[Option[Any]] = functions map { f =>
messages.find(f.isDefined).map(f)
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我需要以人类可读的形式(用于记录)得到"我所期望的"到"我所拥有的"的地图.说,
(case "foo") -> Some(R1)
(case Int if _ > 10) -> Some(R2)
(case Boolean) -> None
Run Code Online (Sandbox Code Playgroud)
那可能吗?一些宏/元作品?
感谢您的回答。使用宏是有趣的一种选择。但作为一种选择,解决方案可能是使用某种命名的部分函数。这个想法是命名函数,以便在输出中您可以看到函数的名称而不是源代码。
object PartialFunctions {
type FN[Result] = PartialFunction[Any, Result]
case class NamedPartialFunction[A,B](name: String)(pf: PartialFunction[A, B]) extends PartialFunction[A,B] {
override def isDefinedAt(x: A): Boolean = pf.isDefinedAt(x)
override def apply(x: A): B = pf.apply(x)
override def toString(): String = s"matching($name)"
}
implicit class Named(val name: String) extends AnyVal {
def %[A,B](pf: PartialFunction[A,B]) = new NamedPartialFunction[A, B](name)(pf)
}
}
Run Code Online (Sandbox Code Playgroud)
那么你可以按如下方式使用它
import PartialFunctions._
val pm1: PartialFunction[Any, Any] = "\"foo\"" % {
case "foo" => R1
}
val pm2: PartialFunction[Any, Any] = "_: Int > 10" % {
case x: Int if x > 10 => R2
}
val pm3: PartialFunction[Any, Any] = "_: Boolean" % {
case x: Boolean => R3
}
val messages: List[Any] = List("foo", 20)
val functions = List(pm1, pm2)
val found: List[Option[(String, Any)]] = functions map { case f: NamedPartialFunction =>
messages.find(f.isDefined).map(m => (f.name, f(m))
}
Run Code Online (Sandbox Code Playgroud)