Scheme 中的递归(或 while 循环)

标签 recursion while-loop scheme

(define (orderedTriples n)
(set! i n)
(set! j n)
(set! k n)
(while (>= i 0)
   (while (>= j 0)
     (while (>= k 0)
       (printf "(~a, ~a, ~a)" i j k) 
       (set! k (- k 1))) 
     (set! j (- j 1))) 
  (set! i (- i 1))))

所以我的问题是......我对如何使 while 循环在方案中工作感到困惑(我对此很陌生,所以如果我不太了解,请原谅语法)。我在这里打字只是为了解决问题并展示我想要完成的任务。谁能帮我一个简单的递归示例或嵌套递归?

最佳答案

根据所使用的Scheme解释器,有多种方法可以实现所需的循环。例如,在 Racket 中,就像使用 iterations and comprehensions 一样简单:

(define (orderedTriples n)
  (for* ([i (in-range n -1 -1)]
         [j (in-range n -1 -1)]
         [k (in-range n -1 -1)])
    (printf "(~a, ~a, ~a)" i j k)))

问题中显示的编程风格(假设它有效)在Scheme中是非常不鼓励的 - 使用突变(set!操作)进行循环是一个很大的禁忌,这就是你的方式d 用类似 C 的语言解决这个问题,但特别是在 Scheme 中(以及一般的 Lisp 中),还有其他用于在程序中实现迭代的结构(@TerjeD 给出的解决方案演示了 do 的使用) code>,例如),即使这样的构造不存在,递归解决方案或使用 higher-order procedures 的解决方案将是首选。例如,这是另一个可能的解决方案,使用 nested mappings仅使用标准过程(printf 除外,它是非标准的):

(define (range n)
  (if (negative? n)
      '()
      (cons n (range (- n 1)))))

(define (orderedTriples n)
  (for-each (lambda (i)
              (for-each (lambda (j)
                          (for-each (lambda (k)
                                      (printf "(~a, ~a, ~a)" i j k))
                                    (range n)))
                        (range n)))
            (range n)))

关于Scheme 中的递归(或 while 循环),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14678115/

相关文章:

方案:余数函数 - 违反合约

C++/SFML : Printing convex shapes to the screen using two recursive calls only displays the shapes from the first recursive call and not the second

javascript - 从头开始使用递归 getElementsByClassName

c++ - 递归数独求解器几乎可以工作,但空网格会出现堆栈溢出

Bash shell 脚本嵌套 while 循环与 IFS

scheme - 通过 lambda 在Scheme中制作过程

lisp - SICP 2.42 八皇后。帮忙看看我的代码有什么问题?

javascript - 递归模板 Angular2

java - token "System"出现语法错误,删除此 token - 输出无法解析或不是字段

php - while 循环只显示一行?