繁体   English   中英

在Scala中组成部分函数

[英]Composing partial functions in Scala

我有两个局部函数f1f2 ,它们想组成一个新的局部函数f以便f.isDefinedAt(x) iff f1.isDefinedAt(x) || f2.isDefinedAt(x) f1.isDefinedAt(x) || f2.isDefinedAt(x) 我的意思是

        --
       | f1(x) iff f1.isDefinedAt(x)  
       |
f(x) = |
       |
       | f2(x) iff  !f1.isDefinedAt(x) && f2.isDefinedAt(x)  
        --

有没有办法用这种方式组合f1f2

使用PartialFunctionorElse

f1 orElse f2

使用方法.orElsePartialFunction

scala> val f1: PartialFunction[Int, Unit] = { case x if x > 0 => println(s"called f1 with $x") }
f1: PartialFunction[Int,Unit] = <function1>

scala> val f2: PartialFunction[Int, Unit] = { case x if x < 0 => println(s"called f2 with $x") }
f2: PartialFunction[Int,Unit] = <function1>

scala> (f1 orElse f2)(1)
called f1 with 1

scala> (f1 orElse f2)(-1)
called f2 with -1

scala> (f1 orElse f2)(0)
scala.MatchError: 0 (of class java.lang.Integer)
  at scala.PartialFunction$$anon$1.apply(PartialFunction.scala:253)
  at scala.PartialFunction$$anon$1.apply(PartialFunction.scala:251)
  at $anonfun$1.applyOrElse(<console>:11)
  at $anonfun$1.applyOrElse(<console>:11)
  at scala.runtime.AbstractPartialFunction$mcVI$sp.apply$mcVI$sp(AbstractPartialFunction.scala:36)
  at scala.runtime.AbstractPartialFunction$mcVI$sp.apply(AbstractPartialFunction.scala:36)
  at scala.runtime.AbstractPartialFunction$mcVI$sp.apply(AbstractPartialFunction.scala:28)
  at $anonfun$1.applyOrElse(<console>:11)
  at $anonfun$1.applyOrElse(<console>:11)
  at scala.PartialFunction$OrElse.apply(PartialFunction.scala:167)
  at scala.Function1$class.apply$mcVI$sp(Function1.scala:36)
  at scala.PartialFunction$OrElse.apply$mcVI$sp(PartialFunction.scala:164)
  ... 32 elided

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM