Why doesn’t the following code doesn’t work?
fun sum_list xs =
case xs of
[] => NONE
| x::xs' => SOME (x+sum_list xs')
This code works well when Instead of NONE it is zero and when I remove SOME. I know that for sum of an empty list zero is the reasonable answer. But why does the following example fails?
Update: Made it work by following Diego’s Answer:
fun sum_list xs =
case xs of
[] => NONE
| x =>
let
fun slist x =
case x of
[] => 0
| x::xs' => x + slist xs'
in
SOME (slist x)
end
The problem is that the function is made to return an
'a optionbut in the lat expression you use it as if it returned an int:You have to either build an internal function that works solely in lists and return numbers (not options), and then box the final result into an option, or eval the result of
sum_listwhen returned to see if it contains a value or it isNONE. I can write both ways, but you should try before seeing the solution written.