Lisp SICP的一个程序

#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)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值