Partial functions
In the previous chapter, we looked at partially applied functions. We left one or more arguments unspecified, and as a result, we got another function. There are partially applied functions and there are partial functions. So, what do we mean by the term partial functions? It simply means that such a function is not defined for some values. Let's try the following example of a partial function:
scala> val f = (x: Int, y: Int) => x / y f: (Int, Int) => Int = <function2> scala> f(12, 3) res0: Int = 4 scala> f(12, 0) java.lang.ArithmeticException: / by zero at $anonfun$1.apply$mcIII$sp(<console>:10) ... 33 elided
Here, we have a function that takes two integer parameters, x
and y
. It divides x
by y
. When we pass 0
as the value of y
, we get a division by 0
. The function f
is not defined for a subset of possible values. Or rather, as it is partially defined for some values, it is a partially defined function. It is defined only for some values...