Scala,部分函数

| 除了通过
case
语句,是否有任何方法可以创建
PartialFunction
? 我很好奇,因为我想表达以下内容(标量伪向前!)...
val bi = BigInt(_)
if (bi.isValidInt) bi.intValue
...作为部分功能,并在
val toInt : PartialFunction[String, Int] = {
    case s if BigInt(s).isValidInt => BigInt(s).intValue
}
似乎多余,因为我两次创建了4ѭ。     
已邀请:
不知道我明白这个问题。但是,这是我的尝试:为什么不创建提取器?
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
}
另一种选择是(这可能会回答一个问题,即是否可以使用
case
文字创建create0ѭ):
val toInt = new PartialFunction[String, Int] {
  def isDefinedAt(s: String) = BigInt(s).isValidInt
  def apply(s: String) = BigInt(s).intValue
}
但是,由于部分函数的想法只是部分定义,因此最终您仍然会做多余的事情-您需要创建一个大int来测试其是否有效,然后在函数中再次创建big int的应用程序... 我在Github上看到一个项目,试图通过缓存ѭ9的结果来解决这个问题。如果您遵循基准测试,您会发现它比默认的Scala实现要慢:) 因此,如果您想避开
isDefinedAt
apply
的双重性质,则应该直接使用提供(
Option[Int]
)的(完整)函数。     
我认为您正在寻找升降机。 lift使用部分函数并将其转换为返回Option的函数。 Unlift接受具有一个参数的函数,该参数返回一个选项,并返回一个部分函数。
import scala.util.control.Exception._

scala> def fn(s: String) = catching(classOf[NumberFormatException]) opt {BigInt(s)}
fn: (s: String)Option[scala.math.BigInt]

scala> val fnPf = Function.unlift(fn)
fnPf: PartialFunction[String,scala.math.BigInt] = <function1>

scala> val fn = fnPf.lift
fn: String => Option[scala.math.BigInt] = <function1>
密切相关,您还想查看以下答案以获取有关cond和condOpt的信息:
scala> import PartialFunction._
import PartialFunction._

scala> cond(\"abc\") { case \"def\" => true }
res0: Boolean = false

scala> condOpt(\"abc\") { case x if x.length == 3 => x + x }
res1: Option[java.lang.String] = Some(abcabc)
    
如果您愿意,可以写出
PartialFunction
\“ longhand \”:
object pf extends PartialFunction[Int,String] {
  def isDefinedAt(in: Int) = in % 2 == 0

  def apply(in: Int) = {
    if (in % 2 == 0) 
      \"even\" 
    else 
      throw new MatchError(in + \" is odd\")
}
    
好,我知道了
import java.lang.NumberFormatException
import scala.util.control.Exception._

val toInt: PartialFunction[String, Int] = {
  catching(classOf[NumberFormatException]) opt BigInt(_) match {
    case Some(bi) if bi.isValidInt => bi.intValue
  }
}
    
这个怎么样?
val toInt: PartialFunction[String, Int] = (s: String) => BigInt(s) match {
  case bi if bi.isValidInt => bi.intValue
}
    

要回复问题请先登录注册