【问题标题】:SML: How can I simulate a counter in SML without having an additional argumentSML:如何在 SML 中模拟计数器而无需附加参数
【发布时间】:2015-04-07 06:40:32
【问题描述】:

我在 SML 中有一个递归函数,它执行某种计算,这对我的问题并不重要。我想要做的是我想跟踪递归发生的次数,就像我想计算我的算法的迭代一样。我知道例如我声明:

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

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

有什么方法可以跟踪吗?

【问题讨论】:

  • 如果必须,您可以在 SML 中执行命令式编程来实现这一点(我相信您会从这些方面得到一些答案)。但通常这是一个错误,会导致更脆弱,在这种情况下,甚至会导致代码变慢。要问的问题是你为什么想要这样做?

标签: recursion functional-programming sml


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 2023-04-11
    • 2016-02-24
    相关资源
    最近更新 更多