当形式参数用作方案中的值时,无法理解我们如何将程序作为实际参数?

时间:2016-07-13 20:18:56

标签: scheme sicp mit-scheme continued-fractions

在SICP练习1.37

Section 1.3.3 in SICP向下滚动到部分结尾(在1.3.4之前)以找到练习[本节中的第3个练习]。

根据问题,我将cont-frac定义为

(define (cont-frac n d k)
    (if (= k 0)
     0 
     (/ n (+ d (cont-frac n d (- k 1))))
    )
)

Link to solution for the exercise

根据解决方案链接,上述代码似乎是一致的。 当解决方案的部分(a)中的n和d被替换为(lamda (i) 1.0)时,问题的第二部分出现问题,这是一个过程。

cont-frac的程序中替换时,我无法理解这是如何工作的。当我尝试时,会出现错误,其中错误的参数类型

编辑1

我添加了我的整个解决方案。它解决了问题,但没有捕捉到该部分的本质。这是练习1.37,1.38和1.39的解决方案。 该程序不使用 过程作为常规方法 ,以下链接的解决方案为Solution to 1.37Solution to 1.38Solution to 1.39

在以下程序中 在程序phie-2-val中,k是连续分数中的步骤 在过程tan中,k是以弧度表示的角度(对于准确值,步数为1000)

#!/usr/local/bin/guile \
-e main -s
!#
(define (finite-cont-frac n d k)
    (if (= k 0)
        0 
        (/ n (+ d (finite-cont-frac n d (- k 1))))))

(define (e-2 n d k1 c k)
    (define (d-val) 
        (if (= (modulo k1 3) 1)
            (+ c 2)
            1))
    (define (c-val)
        (if (= (d-val) 1) c (d-val)))
    (if (= k 0)
        0 
        (/ n (+ (d-val) (e-2 n (d-val) (+ k1 1) (c-val) (- k 1))))))

(define (tan-cf n k d k1)
    (define (d-val)
        (if (= k1 0) 1 (+ d 2)))
    (if (= k 0) 
        0
        (/ n (+ (d-val) (tan-cf n (- k 1) (d-val) (+ k1 1))))))

(define (tan-man x kk)
    (let ((a (- (* x x))))
        (tan-cf a kk 1 0)))
(define rrr 80.0)
(define (main args)
    (let* ((k (string->number (list-ref args 1)))
           (phi (/ 1.0 (finite-cont-frac 1.0 1.0 k)))
           (e-2-val (e-2 1.0 1 0.0 0 k))
           (tt (/ (tan-man k 1000) (- 0.0 k))))
        (display tt)
        (newline)))

1 个答案:

答案 0 :(得分:1)

链接的答案看起来不对,你应该通过程序,而不是数字作为实际参数。使用名为accumulate的帮助程序:

(define (accumulate combiner null-value term1 term2 a next b)
  (if (> a b)
      null-value
      (combiner (term1 a)
                (term2 a)
                (accumulate combiner
                            null-value
                            term1
                            term2
                            (next a)
                            next
                            b))))

(define (cont-frac n d k)
  (accumulate (λ (x y rec) (/ x (+ y rec)))
              0 n d 1 add1 k))

现在我们可以按预期调用该程序:

(cont-frac (lambda (i) 1.0)
           (lambda (i) 1.0)
           10)
=> 0.6179775280898876
相关问题