If you want to define a function which combines two functions in such a way that the second function is evaluated when the first function fails to provide a value for it, you would have to handle the Match
exception which is raised when the first function fails:
val x = fn 5 => 5
| 6 => 6;
val y = fn 3 => 3
| 2 => 2;
val z = fn i => x i
handle Match => y i;
This is somewhat ugly since arguably handle
isn't really in the spirit of functional programming, but it does solve the problem. A cleaner solution would be to have z
return an int option
, but that would change the return type of your functions. The result could look like:
val x = fn 5 => SOME 5
| 6 => SOME 6
| _ => NONE
val y = fn 3 => SOME 3
| 2 => SOME 2
| _ => NONE
val z = fn i => case x i of
SOME j => SOME j
| NONE => y i;
This result was the advantage of silencing all compiler warnings, but you would need to use pattern matching (the way z
does) in any calling function to interpret the output. Note that pattern matching is able to extract the value. In this case, z
just forwarded SOME j
, but it could have used the integer value j
directly if it needed to. See this question for more about options.