chili 默默学编程

SICP(2):LISP 语法


本文目录:

1、Mac 安装 lisp

2、lisp 基本语法

3、应用例子(计算平方根)


Mac 安装 lisp

1、下载对应的安装包(x86-64 版本)

http://www.gnu.org/software/mit-scheme/

2、在终端输入两条命令

sudo ln -s /Applications/MIT\:GNU\ Scheme.app/Contents/Resources /usr/local/lib/mit-scheme-x86-64

sudo ln -s /usr/local/lib/mit-scheme-x86-64/mit-scheme /usr/local/bin/scheme

然后在终端输入 scheme 就启动 scheme 了


lisp 基本语法

详细的教程:http://deathking.github.io/yast-cn/contents/chapter1.html

一个语言包括三个因素:

  • 基本元素(primitive elements)
  • 组合方式(means of combinations)
  • 抽象方式(means of abstraction)


lisp 基本元素:

operand:3,17.4,5

operator:+


lisp 组合方式:前缀表示法

(+ 3 17.4 5)
(+ 3 (* 5 6) 8 2)


lisp 抽象方式:

(define a (* 5 5))
(define (square x)
        (* x x))

(define square (lambda (x) (* x x)))
(define (average x y)
        (/ (+ x y) 2))

(define (mean-average x y)
        (average (square x) (square y)))

条件判断:

(define (abs x)
        (cond ((< x 0) (- x))
              ((= x 0) (0))
              ((> x 0) x)))

(define (abs x)
        (if (< x 0)
        (- x)
        x))

应用例子(计算平方根)

// ----- 我写的 -----
(define (abs x)
        (if (< x 0)
            (- x)
            x)) 

(define (sqrt x a d)
        (if (< (abs (- a (/ x a))) d)
            a
            (sqrt x (/ (+ a (/ x a)) 2) d))))


// ----- 课堂上的思路 -----
(define (sqrt x) (try 1 x))

(define (try guess x)
        (if (good-enough? guess x)
            guess
            (try (improve guess x) x)))

(define (improve guess x)
        (average guess (/ x guess)))

(define (good-enough? guess x)
        (< (abs (- (square guess) x)) 0.001))


// ----- 另一种写法:封装 -----
(define (sqrt x) 
        (define (good-enough? guess)
                (< (abs (- (square guess) x)) 
                   0.001))

        (define (improve guess)
                (average guess (/ x guess)))

        (define (try guess)
                (if (good-enough? guess)
                    guess
                    (try (improve guess)))
      (try 1))


reply ( 0 )