Scala,偏函数 [英] Scala, partial functions

查看:47
本文介绍了Scala,偏函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了通过 case 语句之外,还有什么方法可以创建 PartialFunction 吗?

Is there any way to create a PartialFunction except through the case statement?

我很好奇,因为我想表达以下内容(scala伪提前!)...

I'm curious, because I'd like to express the following (scala pseudo ahead!)...

val bi = BigInt(_)
if (bi.isValidInt) bi.intValue

... 作为偏函数,并且做

... as a partial function, and doing

val toInt : PartialFunction[String, Int] = {
    case s if BigInt(s).isValidInt => BigInt(s).intValue
}

似乎是多余的,因为我创建了两次 BigInt.

seems redundant since I create a BigInt twice.

推荐答案

不确定我是否理解问题.但这是我的尝试:为什么不创建一个提取器?

Not sure I understand the question. But here's my attempt: Why not create an extractor?

object ValidBigInt {
  def unapply(s: String): Option[Int] = {
    val bi = BigInt(s)
    if (bi.isValidInt) Some(bi.intValue) else None
  }
}

val toInt: PartialFunction[String, Int] = {
  case ValidBigInt(i) => i
}

另一种选择是(这可以回答是否可以创建 PartialFunction 而不是使用 case 文字的问题):

The other option is (and that may answer the question as to whether one can create PartialFunction other than with a case literal):

val toInt = new PartialFunction[String, Int] {
  def isDefinedAt(s: String) = BigInt(s).isValidInt
  def apply(s: String) = BigInt(s).intValue
}

但是由于偏函数的想法是它只是部分定义,最后你还是会做多余的事情——你需要创建一个大int来测试它是否有效,然后在你创建的函数应用程序中又是大整数...

However since the idea of a partial function is that it's only partially defined, in the end you will still do redundant things -- you need to create a big int to test whether it's valid, and then in the function application you create the big int again...

我在 Github 上看到了一个项目,该项目试图通过缓存结果来自 isDefinedAt.如果你深入到基准测试,你会发现它比默认的 Scala 实现要慢:)

I saw a project at Github that tried to come around this by somewhat caching the results from isDefinedAt. If you go down to the benchmarks, you'll see that it turned out to be slower than the default Scala implementation :)

因此,如果您想解决 isDefinedAtapply 的双重性质,您应该直接使用提供 Option 的(完整)函数[Int] 结果.

So if you want to get around the double nature of isDefinedAt versus apply, you should just go straight for a (full) function that provides an Option[Int] as result.

这篇关于Scala,偏函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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