Scala full function as partial function

Since a full function is a special case of a partial function, I think I should return the function when I need a partial.

For example,

def partial : PartialFunction[Any,Any] = any => any 

Of course, this syntax cannot be compiled. My question is: is it possible to do this, and if so, then what do I need to do to get the syntax correctly.

I know I can do the following, but this is just a matter of curiosity

 def partial : PartialFunction[Any,Any] = { case any => any } 
+7
scala
source share
4 answers

You can use the PartialFunction.apply method:

 val partial = PartialFunction[Any,Any]{ any => any } 

You can import this method if you want to make it shorter:

 import PartialFunction.{apply => pf} val partial = pf[Any,Any]{ any => any } 
+10
source share

A FunctionN not a complete function:

val evilFun: Int => Int = n => if (n < 0) sys.error("I'm evil!") else n

In other words, all Scala functions are partial functions. Therefore, PartialFunction simply gives you the ability to test a partial function through isDefinedAt and partial chain functions through orElse .

It would be wise to get rid of PartialFunction in general and have isDefinedAt at the FunctionN level with function literals and canceled methods that implement isDefinedAt , as always true .

+4
source share

I think you can switch the concept.

 PartialFunction[-A, +B] extends (A) β‡’ B 

However, you cannot use the value of a superclass where a subclass is expected, because the subclass is more specific. Thus, you cannot return the value of Function1 from the method entered to return the PartialFunction .

The converse works, though - you can use a subclass where a superclass is expected . Thus, you can return the PartialFunction from the method dialed to return Function1 (with the same parameters):

 scala> def f: Any => Any = { case a => "foo" } f: Any => Any scala> f(1) res0: Any = foo 

In this particular case, you can always convert Function to PartialFunction , so the PartialFunction.apply method is PartialFunction.apply .

 def apply[A, B](f: A => B): PartialFunction[A, B] = { case x => f(x) } 
+1
source share

I think you're looking for a convenience method called an β€œelevator” that turns an incomplete function into function1 (returning a result wrapped in an option).

http://www.scala-lang.org/api/current/index.html#scala.PartialFunction

speaking of taxonomy; I think you got it back - a partial function is a subtype of a function

-4
source share

All Articles