SML:如何在没有额外参数的情况下模拟 SML 中的计数器

SML: How can I simulate a counter in SML without having an additional argument

我在 SML 中有一个递归函数,它执行某些与我的问题无关紧要的计算。我想做的是我想跟踪递归发生的次数,就像我想计算算法的迭代次数一样。我知道例如我是否声明:

val counter = 0;
val counter = counter + 1;

另一个计数器是一个不同的变量。它不是同一个加一。所以这种类型的递增将在一次递归调用中失去它的范围。

有什么办法可以跟踪吗?

您可以使用 int ref 作为可变单元格:

val counter : int ref = ref 0

-- Some dummy recursive function for testing
fun factorial n =
  if n < 1
  then 1
  else (counter := !counter + 1; n * factorial (n - 1))

你可以这样使用它:

- !counter;
val it = 0 : int
- factorial 10;
val it = 3628800 : int
- !counter;
val it = 10 : int
- factorial 5;
val it = 120 : int
- !counter;
val it = 15 : int