SML How to define proper option

跟風遠走 提交于 2019-12-19 10:22:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!