我如何声明接受数字和数字列表的函数,如果列表中没有这样的数字则返回 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/