Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala total function as partial function

Since a total function is a special case of a partial function, I think I should be able to return a function when I need a partial.

Eg,

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

Of course this syntax fails to compile. My question is, is it possible to do this, and if so what do I need to do to get the syntax right.

I know I can do the following, but this is just an out-of-curiousity-question

def partial : PartialFunction[Any,Any] = {
  case any => any
}
like image 316
sksamuel Avatar asked Jan 02 '14 20:01

sksamuel


People also ask

What is a partial function in Scala?

A partial function is a function that does not provide an answer for every possible input value it can be given. It provides an answer only for a subset of possible data, and defines the data it can handle. In Scala, a partial function can also be queried to determine if it can handle a particular value.

Can a partial function be Injective?

Many properties of functions can be extended in an appropriate sense of partial functions. A partial function is said to be injective, surjective, or bijective when the function given by the restriction of the partial function to its domain of definition is injective, surjective, bijective respectively.

How do you use andThen in Scala?

Val functions inherit the andThen function and we will show how to use the andThen function to compose two functions together. Mathematically speaking, (f andThen g)(x) = g(f(x)). The results of the first function f(x) is ran first and will be passed as input to the second function g(x).

What is partial function example?

Another example of a partial function is given by y = x + 1 x2 − 3x + 2 , assuming that both the input and output domains are R. This partial function “blows up” for x = 1 and x = 2, its value is “infinity” (= ∞), which is not an element of R. So, the domain of f is R − {1,2}.


1 Answers

You could use PartialFunction.apply method:

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

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

import PartialFunction.{apply => pf}
val partial = pf[Any,Any]{ any => any }
like image 125
senia Avatar answered Sep 23 '22 01:09

senia