[lisp] scheme环境搭建与编译运行

搭建环境参考这篇

http://leochin.com/mac-scheme-install/

用文本编辑器写代码 保存文件格式为 .scm

在终端中cd到scm文件所在文件夹,

执行  (cf "scm_name")编译文件

然后执行 (load "scm_name.scm")加载文件,加载过程中会把文件执行一遍,就像Python一样,或者应该反过来说。

下面是几个lisp程序,参考书籍  SICP

求余:

1 (define (remainder m n)(
2         if (< (- m n) n)
3         (- m n)
4         (remainder (- m n) n)
5     )
6 )

牛顿法求开方:

 1 (define (sqrt x)
 2 (define (sqrt_iter guess x)
 3 (if (good_enough? guess x)
 4  guess
 5  (sqrt_iter (improve_guess guess x)
 6  x )))
 7 
 8 
 9 (define (improve_guess guess x)
10 (average guess (/ x guess)))
11 
12 (define (average a b)
13 (/ (+ a b) 2))
14 
15 (define (good_enough? guess x)
16 (< (abs (- (square guess) x)) 0.001))
17 
18 (define (square x) (* x x))
19 
20 (define (abs x)
21 (if (< x 0)
22 (- x)
23 x)
24 )
25 (sqrt_iter 1.0 x)
26 )

阶乘:

1 (define (factorial n)
2     (fact_iter 1 1 n))
3 
4 (define (fact_iter res count n)
5     (if (> count n)
6         res
7         (fact_iter (* res count) (+ count 1) n)))

 求幂:

 1 (define (expt x n)(
 2     expt_iter x 1 n)
 3 )
 4 
 5 (define (expt_iter x res n)(
 6         if (= n 0)
 7             res
 8             (expt_iter x (* x res) (- n 1))
 9     )
10 )

 最大公约数:

 (define (gcd m n)(
    if (= n 0)
        m
        (gcd n (remainder m n))
))

 fibonacci:

1 (define (fib n)
2    (fib_iter 1 0 n) )
3 
4 (define (fib_iter next pre count)(
5     if (= count 0)
6         pre
7         (fib_iter (+ pre next) next (- count 1))
8 ))

 

1 (define (fib n)
2         (if (< n 2)
3              1
4         (+ (fib (- n 1))
5            (fib (- n 2)))))

 

posted @ 2017-10-02 21:55  wilderness  阅读(1090)  评论(0编辑  收藏  举报