Scala 模式匹配印刷精美 [英] Scala Pattern Matching pretty printed

查看:50
本文介绍了Scala 模式匹配印刷精美的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能以某种方式将 PartialFunction(假设它始终只包含一个案例)编组为人类可读的?

Is that possible to somehow marshall PartialFunction (let's assume it will always contains only one case) into something human-readable?

假设我们有 Any 类型的集合(消息:List[Any])以及使用模式匹配块定义的 PartialFuntion[Any, T] 的数量.

Let's say we have collection of type Any (messages: List[Any]) and number of PartialFuntion[Any, T] defined using pattern matching block.

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)

然后我们可以找到所有与提供的PFs和相关应用程序匹配的消息

then we can find all the messages matched by provided PFs and related applications

val found: List[Option[Any]] = functions map { f =>
  messages.find(f.isDefined).map(f)
}

但是如果我需要以人类可读形式(用于日志记录)生成的我所期望的"到我所拥有的"的地图,该怎么办?说,

but what if I need resulting map of 'what I expect' to 'what I've got' in the human-readable form (for logging). Say,

(case "foo")         -> Some(R1)
(case Int if _ > 10) -> Some(R2)
(case Boolean)       -> None

这可能吗?一些宏/元作品?

Is that possible? Some macro/meta works?

推荐答案

感谢您的回答.使用宏是一种有趣的选择.但作为一种选择,解决方案可能是使用某种命名的部分函数.我们的想法是命名函数,以便在输出中您可以看到函数的名称而不是源代码.

Thanks for your answers. Using Macro is interesting one choice. But as an option the solution might be to use kind of named partial functions. The idea is to name the function so in the output you can see the name of function instead source code.

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

}

那么你就可以这样使用了

So then you can use it as follows

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

这篇关于Scala 模式匹配印刷精美的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆