In Scala, a Partial Function is a function that is only defined for certain input values and may not produce a valid output for all possible inputs. A Total Function, on the other hand, is a function that produces a valid output for any input value within its domain.
Let’s dive into more details for each type of function:
1. Total Function:
A total function is a function that is defined for every input value in its domain. In other words, for every input x in the domain of the function, it must provide a corresponding output value y. Mathematically, a total function can be represented as:
f : A → B
where A is the domain of the function, B is the codomain, and f is the total function. For instance, in Scala, a simple total function could be:
val totalFunction: Int => Int = x => x * 2
In this example, the function is defined for every ‘Int‘ input and returns its double as output.
2. Partial Function:
A partial function is a function that is defined for only a subset of its domain. It is incapable of processing every input value within its domain. Mathematically, a partial function can be represented as:
f : A_subset → B
where A_subset is the subset of the domain A, and f is the partial function.
In Scala, a partial function is represented using the ‘PartialFunction‘ trait. It inherits from the ‘Function‘ trait and adds the ‘isDefinedAt‘ method, which checks if the given input lies within the defined subset of the domain.
Here’s an example of a partial function that only processes positive integers:
val partialFunction: PartialFunction[Int, Int] = {
case x if x > 0 => x * 2
}
This partial function will only process positive integers and double them. For other integers, the function is not defined, and using it on such inputs will result in an exception. You can check if a value is within the defined domain using the ‘isDefinedAt‘ method:
partialFunction.isDefinedAt(-1) // Returns false
partialFunction.isDefinedAt(5) // Returns true
In summary, the main difference between a total function and a partial function in Scala is their defined domain. A total function is defined for all input values within its domain, while a partial function is only defined for a subset of its domain.