如果此代码具有基本情况,为什么会在 SML 中生成无限递归?

问题描述

我用 NJ Compiler 用 SML 编写了以下代码

fun all_answers (f,xs) = 
    let 
        fun aux(accu,xs_left) = 
            case xs of
               [] => SOME accu
            | x::xs' => case f(x) of 
                          NONE => NONE
                        | SOME y => aux(accu@y,xs')
    in
        aux([],xs)
    end

它适用于这个测试:

val testAll1 = all_answers ((fn x => if x = 1 then SOME [x] else NONE),[]) = SOME []
val testAll2 = all_answers ((fn x => if x = 1 then SOME [x] else NONE),[2,3,4,5,6,7]) = NONE

然而,这个测试发生了一些奇怪的事情:

val testAll3 = all_answers ((fn x => if x = 1 then SOME [x] else NONE),[1]) = SOME [1]

运行程序后,终端一直运行。

我定义了尾递归,并使用与 xs' 的模式匹配来到达尾。

此外,我定义了基本情况来结束递归,这样如果 xs[],那么辅助函数返回 SOME accumulator

有人可以帮我吗?

提前致谢。

解决方法

正如@kopecs 指出的,这是由 case xs of 当您想要 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-of 中执行 case xs of。 (2) 去掉内部的 aux 函数,简单地在外部函数中进行递归,代价是一些尾递归

第一个简化可能如下所示:

fun all_answers2 (f,[]) = SOME accu
          | aux (accu,x::xs) =
               case f x of
                    NONE => NONE
                  | SOME y => aux (accu@y,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,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,因为它遵循一元设计模式。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...