1
votes

I'm creating sum of list and using option in it. When I pass an empty list, I should get NONE or else SOME value.

I'm able to do that in the following way:

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

But I want to do it in the other way round using pattern matching, in which I want to eval the result of sum_list to see whether it is NONE or contains some other value.

I have tried in various ways but I cannot get a hang of how to do in that way.

1

1 Answers

4
votes

I think what you currently have is very clear and easy to understand.

If you want to avoid using slist, you have to call sum_list recursively on the tail of the list, pattern-match on that option value and return appropriate results:

fun sum_list xs =
    case xs of
       [] => NONE
     | x::xs' => (case (sum_list xs') of
                     NONE => SOME x
                   | SOME y => SOME (x+y))