问题
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
回答1:
The problem is that the function is made to return an 'a option
but in the lat expression you use it as if it returned an int:
x + sum_list xs'
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_list
when returned to see if it contains a value or it is NONE
. I can write both ways, but you should try before seeing the solution written.
来源:https://stackoverflow.com/questions/14552287/sml-how-to-define-proper-option