#lang racket
(define (square x) (* x x))
(define (good-enough? guess x)
(< (abs (- (square guess) x)) 0.01))
(good-enough? 0.11 0.01)
(define (average x y) (/ (+ x y) 2))
(define (improve guess x)
(average guess (/ x guess)))
(define (sqr guess x)
(if (good-enough? guess x)
guess
(sqr (improve guess x)
x)))
(sqr 3 4)
关于平方开根的程序
#lang racket
(define (pisum a b)
(if (> a b)
0
(+ (/ (* a (+ a 2))) (pisum (+ a 1) b))))
(pisum 9 11)
这是个求pi的LISP代码
Lisp中的lambda求值:
#lang racket
(define (square x) (* x x))
((lambda (x y z) (+ x y (square z))) 1 2 3)
((lambda (x) (+ x 4)) 5)
(define plus4 (lambda (x) (+ x 4)))
(plus4 3)
看完以上例子基本上对Lisp的lambda求值有比较深刻的了解了。
#lang racket
(define (sum term a next b)
(if (> a b)
0
(+ (term a)
(sum term (next a) next b))))
(define (inc n) (+ n 1))
(define (cube x) (* x x x) )
(define (sum-cube a b)
(sum cube a inc b))
(sum-cube 1 10)
SICP上面的一个例子
#lang racket
(define (plus4 a) (+ a 4))
(define plus5 (lambda(x) (+ x 5)))
(plus5 5)
(plus4 6)
LISP的消息传递
#lang racket
(define (make-amount balance)
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"insufficient funds"))
(define (deposit amount)
(set! balance (+ balance amount)))
(define (dispatch m)
(cond ((eq? m 'withdraw) withdraw)
((eq? m 'deposit) deposit)
(else (error "unknow request"
m))))
dispatch)
(define acc (make-amount 100))
acc
((acc 'withdraw) 50)