功能"除了一个"

vor*_*192 1 algorithm functional-programming sml

如何声明带数字和数字列表的函数,如果列表中没有这样的数字则返回NONE,否则返回list选项(Haskell中的'Maybe')没有这个数字?如果有多于一个这样的数字,则函数必须首先擦除它们中的第一个.

all_except_one : 'a * 'a list -> 'a list option
Run Code Online (Sandbox Code Playgroud)

我不知道该怎么做:\我问任何语言的代码,只是关于函数式算法的一些提示(最初我必须在SML中解决这个问题).此外,我不能在我的任务中使用高阶函数.

son*_*nia 6

这个解决方案怎么样?

fun all_except_one(s, lst) =
    let
        fun helper e =
            case e of
                ([], _) => NONE
               |(x::xs, acc) => if x = s
                                then SOME (acc @ xs)
                                else helper(xs, x :: acc)
    in helper(lst, []) end
Run Code Online (Sandbox Code Playgroud)

没有辅助函数和没有尾递归的相同.

fun all_except_one (_, []) = NONE
  | all_except_one (s, x::xs) = if x = s
                                then SOME xs
                                else case all_except_one(s, xs) of
                                           NONE => NONE
                                         | SOME ys => SOME (x::ys)
Run Code Online (Sandbox Code Playgroud)