1

我如何声明接受数字和数字列表的函数,如果列表中没有这样的数字,则返回 NONE,否则返回没有这个数字的列表选项(Haskell 中的“可能”)?如果有多个这样的数字,函数必须只删除其中的第一个。

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

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

4

2 回答 2

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)
于 2013-01-26T18:18:00.047 回答
1

怎么样(Haskell语法):

allbutone n xs
    | n `elem` xs = Just (filter (!=n) xs)
    | otherwise   = Nothing
于 2013-01-26T18:09:53.827 回答