设置一个初始值,并计入n,然后返回初始值

时间:2018-10-14 10:33:14

标签: scheme

基本上,我需要设置一个起始值(1)并计入n并返回至1。对于每次计算,我需要显示该值。 这就是我现在所拥有的:

(define (teken-symbolen x y)
  (begin (display x) (display y) (display x)))


(define (teken-n x y n)
  (cond ((or(= n 0) (< n 0)) (display onmogelijk))
        ((= n 1) (teken-symbolen x y))
        (else (begin
                (teken-symbolen x y)
                (teken-n x y (- n 1))))))

这当前只显示值n,而我需要在每行中显示从一个计算值到我的值n的所有计算,然后又在另一行显示所有计算,我认为我可以使用(换行符)。

任何帮助,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

考虑何时会发生什么情况。如果你写

(begin (display 1)
       (display 2)
       (display 3))

数字以什么顺序显示?因此,让我们将其转换为您需要执行的操作。我不知道您为什么认为xy是好的价值,所以我认为您应该有一份合同。因为您已经知道第一个价值(1),所以您只需要{{1} },所以我建议:

n

有些期望

(define (print-to-and-from n)
  ...)

您需要知道自己当前在(print-to-and-from 0) ; nothing printed (or whatever) (print-to-and-from 1) ; 1 printed only once (perhaps) (print-to-and-from 2) ; 1, 2, 1 printed (print-to-and-from 3) ; 1, 2, 3, 2, 1 printed 1等上,因此您需要的绑定不是合同的一部分。您可以使用助手来完成。

2

现在,如果您从(define (print-to-and-from n) (define (helper cur) ; In here you can compare cur to n ; and increase cur on consecutive calls ...) (helper 1)) 2的关系来看32的结果,您将看到{{1 }}与3相同。因此,您希望在默认情况下在下一次递归之前和之后进行打印,以便先打印(print-to-and-from 3),然后再进行(print-to-and-from 2),然后将控件从第一个递归打印出来1步。就像我分析器中的第一个代码一样,第二个2, 3, 2除外是对1的调用。

还要注意,当停止时,即使停止值为display,也只打印一次。因此,您的基本情况仅应打印当前值。

NB 将帮助程序设为全局变量可能会更容易。这是通过lambda提升完成的。例如。使所有闭合变量都绑定一个:

helper

除了需要多写一点之外,这并不会改变程序。好处是您可以单独测试助手。祝你好运!