algorithm - 功能性 "All except one"

标签 algorithm functional-programming sml

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

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

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

最佳答案

这个解决方案怎么样?

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)

关于algorithm - 功能性 "All except one",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14539857/

相关文章:

eclipse - 哪种函数式编程语言在 Eclipse 中提供最好的支持?

types - 结构可以在标准 ML 中实现多个签名吗?

c - 在C中寻找循环单转置 vector

python - 在 knn 算法中计算距离而不是欧氏距离的替代有效方法

Java 8 多级 flatMap 最佳实现

functional-programming - 在 SML 中优雅地打印二维数组

function - 这个函数签名在sml中是什么意思?

algorithm - 打印/输出变量值到即时窗口

algorithm - 如何枚举8-puzzle中的所有状态?

javascript - FP : Reflecting state in absence of actual state change?