let的一个用法
> (let ((fun (lambda (x) (+ 1 x))))
(fun 2))
3let 里面的属性也可以是lambda
序对
cons
一个特殊的数据结构
scheme中只能用两个
例:
> (cons 1 3)
(1 . 3)
> (cons 1 77)
(1 . 77)当使用三个的时候
> (cons 1 2 3)
Exception: incorrect argument count in call (cons 1 2 3)
Type (debug) to enter the debugger.
>car
提取cons中的第一个
例:
> (car (cons 1 2))
1
> (car (cons 2 1))
2cdr
提取cons中的第二个
例:
> (cdr (cons 1 2))
2
> (cdr (cons 2 1))
1‘
‘ 可以看成cons的升级版,不过没有个数限制 。但是还是有区别的
例:
> '(1 2)
(1 2)
> '(1 2 3 4)
(1 2 3 4)区别:
> (cons 1 2)
(1 . 2)
> '(1 2)
(1 2)car
‘ 的car是提取第一个
例:
> (car '(1 2))
1
> (car '(1 2 3 4))
1cdr
‘ 的cdr是提取出去第一个后的结果
例:
> (cdr '(1 2 3 4))
(2 3 4)
> (cdr '(1))
()
> (cdr '(1 2))
(2)car 与cdr 操作 ‘ 不能为空,至少有一个
例:
> (car '())
Exception in car: () is not a pair
Type (debug) to enter the debugger.
> (cdr '())
Exception in cdr: () is not a pair
Type (debug) to enter the debugger.
> (cdr '(1))
()
> (car '(1))
1应用
有理数
用cons完成
分数的表示和提取分子和分母
> (define (make_fraction x y)
(cons x y))
> (define (numerator z)
(car z))
> (define (denominator z)
(cdr z))
>另一种方法
> (define make_fraction cons)
> (define denominator cdr)
> (define numerator car)display
显示后面的数据
例:
> (display "aaa")
aaa
> (display "1/2")
1/2有理数的加法
> (define (add_fraction x y)
(make_fraction (+ (* (numerator x) (denominator y))
(* (numerator y) (denominator x)))
(* (denominator x) (denominator y))))
> (add_fraction (make_fraction 1 2) (make_fraction 1 2))
(4 . 4)有理数的分数显示
> (define (show_fraction x)
(newline)
(display (numerator x))
(display "/")
(display (denominator x))
)
> (show_fraction (make_fraction 1 2))
1/2缺点:当分母为负数的时候会出现
> (show_fraction (make_fraction 1 -2))
1/-2升级版:
> (define (show_fraction x)
(newline)
(if (< (* (denominator x) (numerator x)) 0)
(display "-"))
(display (abs (numerator x)))
(display "/")
(display (abs (denominator x))))
> (define (abs x)
(cond ((< x 0) -x)))
> (show_fraction (make_fraction 1 -2))
-1/2再次完成有理数的加法
> (show_fraction (add_fraction (make_fraction 1 2) (make_fraction 3 4)))
10/8
> (show_fraction (add_fraction (make_fraction 1 -2) (make_fraction 3 -4)))
-10/8本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!