看到第9章了,开始真是看的头大了,所以little scheme就到这里吧。
-
#! /usr/bin/guile -s
-
!#
-
-
;; define function pick, pick the nst atom in the list
-
(define pick
-
(lambda (n lat)
-
(cond
-
((or (zero? n) (null? lat)) '())
-
((zero? (- n 1)) (car lat))
-
(else (pick (- n 1) (cdr lat))))))
-
-
(define looking
-
(lambda (a lat)
-
(keep-looking a (pick 1 lat) lat)))
-
-
(define keep-looking
-
(lambda (a sorn lat)
-
(cond
-
((number? sorn) (keep-looking a (pick sorn lat) lat))
-
(else (eq? sorn a )))))
-
-
;======================================
-
(define first
-
(lambda (p)
-
(cond
-
(else (car p)))))
-
-
(define second
-
(lambda (p)
-
(cond
-
(else (car (cdr p))))))
-
-
(define build
-
(lambda (a1 a2)
-
(cond
-
(else (cons a1 (cons a2 '()))))))
-
-
(define shift
-
(lambda (pair)
-
(build (first (first pair))
-
(build (second (first pair)) (second pair)))))
-
-
-
;===============
-
;length
-
(define length*
-
(lambda (para)
-
(cond
-
((atom? para ) 1)
-
(else (+ (length* (first para)) (length* (second para)))))))
开始翻了翻SICP, 听说前4章对于初学者是有用的,但是感觉对于数学的要求很高。
对我这个文科生,自学计算机的真够难啊。
计算一个数x的平方根的函数sqrt().
假设先猜测x的平方根y ,初始值是y。 则可以通过 (y+x/y)/2 求得一个更好的y值。
-
#! /usr/bin/guile -s
-
!#
-
-
(define (sqrt-iter guess x)
-
(if (good-enough? guess x)
-
guess
-
(sqrt-iter (improve guess x) x)))
-
-
(define (improve guess x)
-
(average guess (/ x guess)))
-
-
(define (average x y)
-
(/ (+ x y) 2))
-
-
(define (good-enough? guess x)
-
(< (abs (- (square guess) x)) 0.001))
-
-
(define (square x)
-
(* x x))
-
-
(define (mysqrt x)
-
(sqrt-iter 1.0 x))
-
-
-
(define (new-if predicate then-clause else-clause)
-
(cond
-
(predicate then-clause)
-
(else else-clause)))
-
-
;never stop
-
(define (sqrt-iter2 guess x)
-
(new-if (good-enough? guess x)
-
guess
-
(sqrt-iter2 (improve guess x) x )))
-
-
(define (mysqrt2 x)
-
(sqrt-iter2 1.0 x))
-
-
-
;another approach to define good-enough3? , this function works very well
-
; for smalle numbers
-
(define (good-enough3? guess prev-guess)
-
(< (abs (- guess prev-guess)) (* 0.001 guess)))
-
-
(define (sqrt-iter3 guess prev-guess x)
-
(if (good-enough3? guess prev-guess)
-
guess
-
(sqrt-iter3 (improve guess x) guess x)))
-
-
-
(define (mysqrt3 n)
-
(sqrt-iter3 1 0 n))
阅读(1647) | 评论(0) | 转发(0) |