正如@kopecs 指出的那样,这是由case xs of
when you want引起的case xs_left of
。
这是您的函数的清理(空格,命名)版本:
fun all_answers (f, ys) =
let
fun aux (accu, xs) =
case xs of
[] => SOME accu
| x::xs' => case f x of
NONE => NONE
| SOME y => aux (accu@y, xs)
in
aux ([], ys)
end
您至少可以做两件事来简化此功能的制作方式。(1) 执行case xs of
函数模式的内部而不是嵌套的 case-of。(2) 移除内部aux
函数,简单地在外部函数中进行递归,代价是一些尾递归
第一个简化可能如下所示:
fun all_answers2 (f, ys) =
let
fun aux (accu, []) = SOME accu
| aux (accu, x::xs) =
case f x of
NONE => NONE
| SOME y => aux (accu@y, xs)
in
aux ([], ys)
end
第二个可能看起来像:
fun all_answers' (f, []) = SOME []
| all_answers' (f, x::xs) =
case f x of
NONE => NONE
| SOME ys => case all_answers' (f, xs) of
NONE => NONE
| SOME result => SOME (ys @ result)
这显示了一个模式:每当你有
case f x of
NONE => NONE
| SOME y => case g y of
NONE => NONE
| SOME z => ...
那么你就有了一个可以用函数抽象出来的编程模式。
已经有一个为此调用的标准库函数Option.map
,因此您可以编写:
fun all_answers3 (f, ys) =
let
fun aux (accu, []) = SOME accu
| aux (accu, x::xs) =
Option.map (fn y => aux (accu@y, xs))
(f x)
in
aux ([], ys)
end
尝试在 REPL 中使用这个函数:
- Option.map (fn y => y + 2) NONE;
> val it = NONE : int option
- Option.map (fn y => y + 2) (SOME 2);
> val it = SOME 4 : int option
将其转向另一个方向,而不是内部功能:
(* Alternative to Option.map: *)
fun for NONE _ = NONE
| for (SOME x) f = f x
(* Equivalent to Option.mapPartial with "flipped" arguments: *)
fun for opt f = Option.mapPartial f opt
fun all_answers'' (f, []) = SOME []
| all_answers'' (f, x::xs) =
for (f x) (fn ys =>
for (all_answers'' (f, xs)) (fn result =>
SOME (ys @ result)))
这种风格更像 Haskell,因为它遵循一元设计模式。