功能“除了一个”

时间:2013-01-26 18:01:23

标签: algorithm functional-programming sml

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

all_except_one : 'a * 'a list -> 'a list option

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

2 个答案:

答案 0 :(得分: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

没有辅助函数且没有尾递归。

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)

答案 1 :(得分:1)

如何(Haskell语法):

allbutone n xs
    | n `elem` xs = Just (filter (!=n) xs)
    | otherwise   = Nothing
相关问题