重学《The Little Schemer》

    Programming Language

重构博客之后,突然就想弥补一下学生时代的遗憾:学习 Daniel P. Friedman 写的系列书籍。以前时间没有那么充裕,Friedman 的书很多地方没时间琢磨,现在感觉是时候了。

在人工智能时代,还有学习程序语言的强烈意愿,不知道是一种无知还是一种睿智。就当成一场轻松的旅途,走到哪算哪吧。

虽然本书的编程语言用的是 Scheme,但我学习过程准备用 Racket 语言,即 DrRacket 这个 IDE 默认的语言。首先因为合著者 Matthias Felleisen 在邮件中肯定了这个做法(当然,他是 Racket 语言的领头人)。其次,掌握书中思想更重要,而不是纠结语言实现上细节的一致性。

如果真的想使用严格传统的 Scheme 标准,应该考虑用 #lang r5rs,而不是 #lang scheme,因为在 DrRackt 中,scheme 也只是 racket 旧名称 PLT Scheme 的兼容入口而已。但就算是 R5RS 也不是 The Little Schemer 的完全对应物。本书用的其实是一种为了教学而精心简化、甚至部分理想化的 Lisp 语言。

#lang racket                ; 用 racket 语言

(define atom?
  (lambda (x)
    (and (not (pair? x))
         (not (null? x)))))

(atom? (quote ()))          ; #f

关于 DrRacket IDE 编辑器,可以参考这篇文章进行配置。

此外,Friedman 的系列书籍中总会有一些奇怪的符号作为变量名,而 DrRacket 恰好自带了一个相当方便的功能:LaTeX 风格的 Unicode 符号输入。这些符号可让我们的代码尽可能与书中保持一致。输入方法如下:

例如,要输入 ↑

  1. 在编辑器中输入 \uparrow
  2. 按 Ctrl + \
  3. DrRacket 会把它转换成 ↑

更多符号参见 DrRacket 官方手册:LaTeX and TeX inspired keybindings


Preface

The goal of this book is to teach the reader to think recursively.

Daniel P. Friedman
Language Characteristics
Natural
Language
Ambiguous, imprecise, and verbose; effective for general communication.
Formal
Mathematics
Precise and concise, but cryptic and difficult to learn.
Programming
Language
Formally precise like mathematics, but executable, observable, and modifiable.
An Ideal choice to communicate the concept of recursion.

The reader must be comfortable reading English, recognizing numbers, and counting.

Daniel P. Friedman

Notational Conventions

Symbol Class Typeface Examples
Variables
&
primitive operations
Italic x, car, cons
Basic data Sans serif Numbers, truth and falsehood
Keywords Boldface define, lambda, cond, else, and, or, quote
Programs in framenotes Typewriter Executable code

Note:
Typeface distinctions can be ignored until Chapter 10, where programs are treated as data. However, the framenotes should not be ignored.

The key to learning scheme is “pattern recognition.”

Daniel P. Friedman

Chapter 1 - Toys

这章介绍表达式的各种基础概念和后续要用的操作符(primitive operations):
car ,cdr ,cons ,null? 和 eq?
本章标题 Toys 也许就指这些 primitive operations ,后续的概念和代码都会用到

An S-expression is either an atom or a collection of S-expressions enclosed by parentheses.

W’s summary
The Law of Car
The primitive car is defined only for non-empty lists.
The Law of Cdr
The primitive cdr is defined only for non-empty lists.
The cdr of any non-empty is always another list.
The Law of Cons
The primitive cons takes two arguments.
The second argument to cons must be a list.
The result is a list.
The Law of Null?
The primitive null? is defined only for lists.
The Law of Eq?
The primitive eq? takes two arguments.
Each must be a non-numeric atom.

Note:
“cdr” is pronounced “could-er”.
(cons a l) is read: “cons the atom a onto the list l.”


Chapter 2 - Do It, Do It Again, and Again, and Again…

本章用各种递归函数一步步引导普及递归的概念
「递归」正如章节名所描述的那样:again and again …

(define lat?    ; a lat is a list of atoms
  (lambda (l)
    (cond
      [(null? l) #t]
      [(atom? (car l)) (lat? (cdr l))]
      [else #f])))


(define member?
  (lambda (a lat)
    (cond
      [(null? lat) #f]
      [else
       (or (equal? a (car lat))       ; eq? → equal? 
           (member? a (cdr lat)))]))) ; for numeric comparison
The First Commandament
( preliminary )
Always ask null? as first question in expressing any function.

Chapter 3 - Cons the Magnificent

本章通过各种函数学习如何用 cons 递归地构建 list:

describe the first typical element, and then cons it onto the natural recursion.

(define rember        ; "rember" stands for remove [a] member
  (lambda (a lat)
    (cond
      [(null? lat) '()]
      [(eq? a (car lat))
       (cdr lat)]
      [else
       (cons (car lat)
             (rember a (cdr lat)))])))
The Second Commandament
Use cons to build lists.
(define firsts             ; firsts takes one argument, a list,
  (lambda (l)              ; which is either a null list or contains
    (cond                  ; only non-empty lists. It builds another
      [(null? l) '()]      ; list composed of the first S-expression
      [else                ; of each internal list.
       (cons (car (car l))
             (firsts (cdr l)))])))
The Third Commandament
When building a lists, describe the first typical element,
and then cons it onto the natural recursion.
(define insertR
  (lambda (new old lat)
    (cond
      [(null? lat) '()]
      [(eq? old (car lat))
       (cons old
             (cons new
                   (cdr lat)))]
      [else
       (cons (car lat)
             (insertR new old (cdr lat)))])))


(define insertL
  (lambda (new old lat)
    (cond
      [(null? lat) '()]
      [(eq? old (car lat))
       (cons new lat)]
      [else
       (cons (car lat)
             (insertL new old (cdr lat)))])))


(define subst
  (lambda (new old lat)
    (cond
      [(null? lat) '()]
      [(eq? old (car lat))
       (cons new (cdr lat))]
      [else
       (cons (car lat)
             (subst new old (cdr lat)))])))


(define subst2             ; replace either the first ocurrence of 
  (lambda (new o1 o2 lat)  ; o1 or the first ocurrence of o2 by new
    (cond
      [(null? lat) '()]
      [(or (eq? o1 (car lat))
           (eq? o2 (car lat)))
       (cons new (cdr lat))]
      [else
       (cons (car lat)
             (subst2 new o1 o2 (cdr lat)))])))


(define multirember
  (lambda (a lat)
    (cond
      [(null? lat) '()]
      [(equal? a (car lat))       ; eq? → equal? 
       (multirember a (cdr lat))] ; for numeric comparison
      [else
       (cons (car lat)
             (multirember a (cdr lat)))])))


(define multiinsertR
  (lambda (new old lat)
    (cond
      [(null? lat) '()]
      [(eq? old (car lat))
       (cons old
             (cons new
                   (multiinsertR new old (cdr lat))))]
      [else
       (cons (car lat)
             (multiinsertR new old (cdr lat)))])))



(define multiinsertL
  (lambda (new old lat)
    (cond
      [(null? lat) '()]
      [(eq? old (car lat))
       (cons new
             (cons old
                   (multiinsertL new old
                                 (cdr lat))))]
      [else
       (cons (car lat)
             (multiinsertL new old
                           (cdr lat)))])))
The Fourth Commandament
( preliminary )
Always change at least one argument while recurring.
It must be changed to be closer to termination.
The changing argument must be tested in the termination condition:
when using cdr, test termination with null?.
(define multisubst
  (lambda (new old lat)
    (cond
      [(null? lat) '()]
      [(eq? old (car lat))
       (cons new
             (multisubst new old (cdr lat)))]
      [else
       (cons (car lat)
             (multisubst new old (cdr lat)))])))

Chapter 4 - Numbers Games

将递归的概念从链表(list)扩展到数字(当前局限于自然数)。
继续用各种函数(数量很多)强化认知递归函数的模式(pattern):
terminating line ,typical element 和 natural recursion

(define o+
  (lambda (n m)
    (cond
      [(zero? m) n]
      [else
       (add1 (o+ n (sub1 m)))])))


(define o-
  (lambda (n m)
    (cond
      [(zero? m) n]
      [else
       (sub1 (o- n (sub1 m)))])))


(define addtup
  (lambda (tup)   ; tup is short for tuple, a list of numbers
    (cond
      [(null? tup) 0]
      [else
       (o+ (car tup)
           (addtup (cdr tup)))])))
The First Commandament
( first revision )
When recurring on a list of atoms, lat, ask two questions about it:
(null? lat) and else.
When recurring on a number, n, ask two questions about it:
(zero? n) and else.
(define ×
  (lambda (n m)
    (cond
      [(zero? m) 0]
      [else
       (o+ n (× n (sub1 m)))])))
The Fourth Commandament
( first revision )
Always change at least one argument while recurring.
It must be changed to be closer to termination.
The changing argument must be tested in the termination condition:
when using cdr, test termination with null?.
when using sub1, test termination with zero?.
The Fifth Commandament
When building a value with o+, always use 0 for the value of the terminating line,
for adding 0 does not change the value of an addition.
When building a value with o*, always use 1 for the value of the terminating line,
for multiplying by 1 does not change the value of a mutiplication.
When building a value with cons, always consider () for the value of the terminating line.
(define tup+
  (lambda (tup1 tup2)    ; can be any length
    (cond
      [(null? tup1) tup2]
      [(null? tup2) tup1]
      [else
       (cons (o+ (car tup1)
                 (car tup2))
             (tup+ (cdr tup1)
                   (cdr tup2)))])))


(define o>
  (lambda (n m)
    (cond
      [(zero? n) #f]
      [(zero? m) #t]
      [else
       (o> (sub1 n)
           (sub1 m))])))


(define o<
  (lambda (n m)
    (cond
      [(zero? m) #f]
      [(zero? n) #t]
      [else
       (o< (sub1 n)
           (sub1 m))])))


;(define o=
;  (lambda (n m)
;    (cond
;      [(zero? m) (zero? n)]
;      [(zero? n) #f]
;      [else
;       (o= (sub1 n)
;           (sub1 m))])))


(define o=
  (lambda (n m)
    (cond
      [(o< n m) #f]
      [(o> n m) #f]
      [else
       #t])))


(define ↑
  (lambda (n m)
    (cond
      [(zero? m) 1]
      [else
       (× n (↑ n (sub1 m)))])))


(define ÷
  (lambda (n m)
    (cond
      [(o< n m) 0]
      [else
       (add1 (÷ (o- n m) m))])))


(define length
  (lambda (lat)
    (cond
      [(null? lat) 0]
      [else
       (add1 (length (cdr lat)))])))


;(define pick
;  (lambda (n lat)    ; 0 < n <= (length lat)
;    (cond
;      [(zero? (sub1 n)) (car lat)]
;      [else
;       (pick (sub1 n)
;             (cdr lat))])))


;(define rempick
;  (lambda (n lat)     ; 0 < n <= (length lat)
;    (cond
;      [(zero? (sub1 n)) (cdr lat)]
;      [else
;       (cons (car lat)
;             (rempick (sub1 n)
;                      (cdr lat)))])))


(define no-nums
  (lambda (lat)
    (cond
      [(null? lat) '()]
      [(number? (car lat))
       (no-nums (cdr lat))]
      [else
       (cons (car lat)
             (no-nums (cdr lat)))])))


(define all-nums
  (lambda (lat)
    (cond
      [(null? lat) '()]
      [(number? (car lat))
       (cons (car lat)
             (all-nums (cdr lat)))]
      [else
       (all-nums (cdr lat))])))


(define eqan?
  (lambda (a1 a2)
    (cond
      [(and (number? a1)
            (number? a2))
       (o= a1 a2)]
      [(or (number? a1)
           (number? a2))
       #f]
      [else
       (eq? a1 a2)])))


(define occur
  (lambda (a lat)
    (cond
      [(null? lat) 0]
      [(eqan? a (car lat))
       (add1 (occur a (cdr lat)))]
      [else
       (occur a (cdr lat))])))


;(define one?
;  (lambda (n)
;    (cond
;      [(number? n) (zero? (sub1 n))]
;      [else
;       #f])))


(define one?
  (lambda (n)       ; n is a nonnegative integer
    (o= n 1)))


(define pick
  (lambda (n lat)   ; 0 < n <= (length lat)
    (cond
      [(one? n) (car lat)]
      [else
       (pick (sub1 n)
             (cdr lat))])))


(define rempick
  (lambda (n lat)    ; 0 < n <= (length lat)
    (cond
      [(one? n) (cdr lat)]
      [else
       (cons (car lat)
             (rempick (sub1 n)
                      (cdr lat)))])))

Chapter 5 - *Oh My Gawd*: It’s Full of Stars

前面章节的递归函数处理的是链表结构的数据:list 内元素都是 atom ;
本章开始是树结构(tree):list 内元素都是 list 了;
因此 (car l) 和 (cdr l) 两部分都要递归;
处理这类链表中包含链表的数据结构的递归函数都带星号 * ,如 rember* ;

All *-functions work on lists that are either

  • empty,
  • an atom consed onto a list, or
  • a list consed onto a list

基本上就是把前几个章节的递归函数都改成星号函数

(define rember*      ; "rember*" is pronounced "rember-star"
  (lambda (a l)
    (cond
      [(null? l) '()]
      [(atom? (car l))
       (cond
         [(eqan? a (car l))
          (rember* a (cdr l))]
         [else
          (cons (car l)
                (rember* a (cdr l)))])]
      [else
       (cons (rember* a (car l))
             (rember* a (cdr l)))])))


(define insertR*
  (lambda (new old l)
    (cond
      [(null? l) '()]
      [(atom? (car l))
       (cond
         [(eqan? old (car l))
          (cons old
                (cons new
                      (insertR* new old (cdr l))))]
         [else
          (cons (car l)
                (insertR* new old (cdr l)))])]
      [else
       (cons (insertR* new old (car l))
             (insertR* new old (cdr l)))])))
The First Commandament
( final version )
When recurring on a list of atoms, lat, ask two questions about it:
(null? lat) and else.
When recurring on a number, n, ask two questions about it:
(zero? n) and else.
When recurring on a list of S-expressions, l, ask three questions about it:
(null? l) , (atom? (car l)) and else.
The Fourth Commandament
( final version )
Always change at least one argument while recurring.
When recurring on a list of atoms, lat, use (cdr lat).
When recurring on a number, n, use (sub1 n).
And when recurring on a list of S-expressions, l, use (car l) and
(cdr l) if neither (null? l) nor (atom? (car l)) are true.
It must be changed to be closer to termination.
The changing argument must be tested in the termination condition:
when using cdr, test termination with null?.
when using sub1, test termination with zero?.
(define occur*
  (lambda (a l)
    (cond
      [(null? l) 0]
      [(atom? (car l))
       (cond
         [(eqan? a (car l))
          (add1 (occur* a (cdr l)))]
         [else
          (occur* a (cdr l))])]
      [else
       (o+ (occur* a (car l))
           (occur* a (cdr l)))])))


(define subst*
  (lambda (new old l)
    (cond
      [(null? l) '()]
      [(atom? (car l))
       (cond
         [(eqan? old (car l))
          (cons new
                (subst* new old (cdr l)))]
         [else
          (cons (car l)
                (subst* new old (cdr l)))])]
      [else
       (cons (subst* new old (car l))
             (subst* new old (cdr l)))])))


(define insertL*
  (lambda (new old l)
    (cond
      [(null? l) '()]
      [(atom? (car l))
       (cond
         [(eqan? old (car l))
          (cons new
                (cons old
                      (insertL* new old (cdr l))))]
         [else
          (cons (car l)
                (insertL* new old (cdr l)))])]
      [else
       (cons (insertL* new old (car l))
             (insertL* new old (cdr l)))])))


(define member*
  (lambda (a l)
    (cond
      [(null? l) #f]
      [(atom? (car l))
       (or (eqan? a (car l))
           (member* a (cdr l)))]
      [else
       (or (member* a (car l))
           (member* a (cdr l)))])))


; finds the left most atom in a non-empty list of
; S-expressions that does not contain the empty list.
(define leftmost
  (lambda (l)
    (cond
      [(atom? (car l)) (car l)]
      [else
       (leftmost (car l))])))


(define eqlist?
  (lambda (l1 l2)
    (cond
      [(and (null? l1)
            (null? l2))
       #t]
      [(or (null? l1)
           (null? l2))
       #f]
      [(and (atom? (car l1))
            (atom? (car l2)))
       (and (eqan? (car l1)
                   (car l2))
            (eqlist? (cdr l1)
                     (cdr l2)))]
      [(or (atom? (car l1))
           (atom? (car l2)))
       #f]
      [else
       (and (eqlist? (car l1)
                     (car l2))
            (eqlist? (cdr l1)
                     (cdr l2)))])))

前面的递归函数都是 Directly Recursion(函数定义中调用自己)
下面首次出现 Mutually Recursion(多个函数在定义中相互调用)

eqlist? 和 equal? 相互调用

; An S-expression is either an atom or 
; a (possibly empty) list of S-expressions
; equal? determines whether two S-expressions are the same

; define equal? in terms of eqlist?
(define equal?
  (lambda (s1 s2)
    (cond
      [(and (atom? s1)
            (atom? s2))
       (eqan? s1 s2)]
      [(or (atom? s1)
           (atom? s2))
       #f]
      [else
       (eqlist? s1 s2)])))


; now rewrite eqlist? using equal?
(define eqlist?
  (lambda (l1 l2)
    (cond
      [(and (null? l1)
            (null? l2))
       #t]
      [(or (null? l1)
           (null? l2))
       #f]
      [else
       (and (equal? (car l1)
                    (car l2))
            (eqlist? (cdr l1)       ; equal? works too here
                     (cdr l2)))]))) ; for all lists are S-expressions
                                    ; and for equal? calls eqlist? in else

有了 equal? 之后,当前除了 eqan? 之外的所有函数中的 eq?(非数字比较) 和 =(数字比较)都可以用 equal? 来替换了。因为 equal? 里调用的 eqan? 就覆盖了数字和非数字两种情况的比较。

The Sixth Commandament
Simply only after the function is correct.
; rewrite rember to remove a S-expression
; from a list of S-expressions
; this new rember fully supersedes the original one
(define rember     
  (lambda (s l)
    (cond
      [(null? l) '()]
      [(equal? s (car l))  ; simply swap eq? for equal? in rember
       (cdr l)]            
      [else                
       (cons (car l)
             (rember s (cdr l)))])))

Chapter 6 - Shadows

这章讲算术表达式(arithmetic expression)。

An arithmetic expression is either an atom (including numbers), or two arithmetic expressions combined by , or

算数表达式是后续的解释器(interpreter)要支持的基本语言结构之一。其他基本语言结构还包括变量(variable),函数(function),调用(call)和数字常量(numbers)。书中从日常常见的中缀表达式(infix)开始介绍,然后过渡到前缀表达式(prefix)。
前缀表达式正是 Scheme 的表达式语法(S-expression)所采用的方式,因为它让语法更具统一性和规律性(所有操作符都在第一个位置),解释器也会因此变得非常简单。

中缀表达式:(9 + 19 + 29)
前缀表达式:(+ 9 19 29)

; numbered? determines whether a representation of
; an arithmetic expression contains only numbers besides
; +, × and ↑
(define numbered?
  (lambda (aexp)    ; aexp stands for "arithmetic expression"
    (cond
      [(number? aexp) #t]
      [else
       (and (numbered? (car aexp))  ; here use infix notation
            (numbered? (car (cdr (cdr aexp)))))])))
The Seventh Commandament
Recur on the subparts that are of the same nature:
• On the sublists of a list.
• On the subexpressions of an arithmetic expression.

本章出现了最简易的解释器函数 value ,后面复杂的解释器就是通过 value 来逐步扩展的。

(define value
  (lambda (nexp)    ; nexp stands for "numbered arithmetic expression"
    (cond
      [(atom? nexp) nexp]
      [(eq? (operator nexp) '+)
       (+ (value (1st-sub-exp nexp))
          (value (2nd-sub-exp nexp)))]
      [(eq? (operator nexp) '×)
       (× (value (1st-sub-exp nexp))
          (value (2nd-sub-exp nexp)))]
      [else
       (↑ (value (1st-sub-exp nexp))
          (value (2nd-sub-exp nexp)))])))


; use help functions to hide the representation
; so we can change notation to infix or prefix (or others)
; without affecting upper-level code (in this case: value)
(define 1st-sub-exp
  (lambda (aexp)
    (car (cdr aexp))))

(define 2nd-sub-exp
  (lambda (aexp)
    (car (cdr (cdr aexp)))))

(define operator
  (lambda (aexp)
    (car aexp)))
The Eighth Commandament
Use help functions to abstract from representation.

这里还展示了如何使用帮助函数(help function)建立抽象层。这样就不必考虑底层的语法到底是中缀还是前缀表达式了。帮助函数会取到对应的部分。语法的改变不影响上层代码,即 value 不受影响。

从帮助函数的抽象(Data Abstraction)进一步引出,我们之前用的数字(numbers)和布尔值(#f 与 #t)也都是抽象,或者说都是一种符号(representation)。我们可以用阿拉伯数字(arabic representation)以外的符号表达数字,比如括号:

() 表示数字 0 的概念
(()) 表示数字 1 的概念
(() ()) 表示数字 2 的概念
(() () ()) 表示数字 3 的概念

用了新符号(representation)后,只要改抽象层函数即可,上层代码无需改:

zero? , add1 和 sub1

(define sero?
  (lambda (n)
    (null? n)))


(define edd1
  (lambda (n)
    (cons '() n)))


(define zub1
  (lambda (n)   ; n can't be sero (null)
    (cdr n)))

这里其实开始涉及计算的本质了:计算的本质就是解释。

观察可以发现,我们的新符号(括号列表)之所以能表示数字的概念,其实是依靠我们同时定义的 sero? , edd1 和 zub1 这些(帮助)函数来建立的。我们靠这三个函数解释了它(括号列表),于是它有了数字的概念。进一步地,有了计算的概念和对应的计算结果。

要注意区分符号(representation)和它指代的意义这两个概念。符号不是数据或概念本身。
符号可以变(比如可中缀、可前缀),但 1st-sub-exp 的概念是不变的。它永远能取到对应的内容。
如果没有做好这种区分(抽象),改变符号(representation)就可能破坏上层代码。

You must beware of shadows.

Daniel P. Friedman

下一本书 The Seasoned Schemer 的 Chapter 19 会再次提到这个 Shadows
Shadow 是要注意别混淆 Representation 和概念本身,不是编程中的 variable shadowing 这一概念

// The inner variable x shadows the outer one.
x => x => x + x

Chapter 7 - Friends and Relations

(define set?
  (lambda (lat)
    (cond
      [(null? lat) #t]
      [(member? (car lat)
                (cdr lat))
       #f]
      [else
       (set? (cdr lat))])))


;(define makeset
;  (lambda (lat)
;    (cond
;      [(null? lat) '()]
;      [(member? (car lat)
;                (cdr lat))
;       (makeset (cdr lat))]
;      [else
;       (cons (car lat)
;             (makeset (cdr lat)))])))


; write makeset using multirember
(define makeset
  (lambda (lat)
    (cond
      [(null? lat) '()]
      [else
       (cons (car lat)
             (makeset (multirember (car lat)
                                   (cdr lat))))])))


(define subset?
  (lambda (set1 set2)
    (cond
      [(null? set1) #t]
      [else
       (and (member? (car set1)
                     set2)
            (subset? (cdr set1)
                     set2))])))


; remember to use subset? above
(define eqset?
  (lambda (set1 set2)
    (and (subset? set1 set2)
         (subset? set2 set1))))


; compare subset? and intersect?
(define intersect?
  (lambda (set1 set2)
    (cond
      [(null? set1) #f]
      [else
       (or (member? (car set1)
                    set2)
           (intersect? (cdr set1)
                       set2))])))


(define intersect
  (lambda (set1 set2)
    (cond
      [(null? set1) '()]
      [(member? (car set1)
                set2)
       (cons (car set1)
             (intersect (cdr set1)
                        set2))]
      [else
       (intersect (cdr set1)
                  set2)])))


(define union
  (lambda (set1 set2)
    (cond
      [(null? set1) set2]
      [(member? (car set1)
                set2)
       (union (cdr set1)
              set2)]
      [else
       (cons (car set1)
             (union (cdr set1)
                    set2))])))


; xxx returns all the atoms in
; set1 that are not in set 2
; Set Difference(差集)
(define xxx
  (lambda (set1 set2)
    (cond
      [(null? set1) '()]
      [(member? (car set1)
                set2)
       (xxx (cdr set1) set2)]
      [else
       (cons (car set1)
             (xxx (cdr set1) set2))])))


(define intersectall
  (lambda (l-set)
    (cond
      [(null? (cdr l-set))  ; assume l-set is non-empty
       (car l-set)]
      [else
       (intersect (car l-set)
                  (intersectall (cdr l-set)))])))

如果说上面的函数都是进一步练习和熟悉递归的概念,那下面这个 pair 就很重要了。pair 是最简单的数据结构,储存两个元素。它可以有很多种实现方式(如数组、对象等),本书是用函数来实现 pair,可以重塑新人对于函数的认知:

函数也是可以储存数据的

; a pair is a list with only two elements
(define a-pair?
  (lambda (l)
    (cond
      [(atom? l) #f]
      [(null? l) #f]
      [(null? (cdr l)) #f]
      [else
       (null? (cdr (cdr l)))])))


(define build
  (lambda (s1 s2)
    (cons s1 (cons s2 '()))))

(define first  ; don't confuse with firsts in Chapter 3
  (lambda (p)
    (car p)))

(define second
  (lambda (p)
    (car (cdr p))))


(define third
  (lambda (p)
    (car (cdr (cdr p)))))


; a finite function is a list of pairs
; in which no first element of any pair
; is the same as any other first element
; distinguish finite function from partial 
; and total function in Page 151
(define fun?
  (lambda (rel)
    (set? (firsts rel))))


;; revrel stands for reverse rel
;(define revrel
;  (lambda (rel)
;    (cond
;      [(null? rel) '()]
;      [else
;       (cons (build (second (car rel))  ; don't forget build
;                    (first (car rel)))  ; representation aids readability
;             (revrel (cdr rel)))])))



; suppose we had the function revpair
(define revpair
  (lambda (pair)
    (build (second pair)
           (first pair))))


; it's even easier to read
(define revrel
  (lambda (rel)
    (cond
      [(null? rel) '()]
      [else
       (cons (revpair (car rel))  ; representation aids readability
             (revrel (cdr rel)))])))


; it's just like firsts
(define seconds
  (lambda (l)
    (cond            
      [(null? l) '()] 
      [else                
       (cons (car (cdr (car l)))
             (seconds (cdr l)))])))


(define fullfun?
  (lambda (fun)
    (set? (seconds fun))))


; one-to-one? is another name for fullfun?
; there's another way to write one-to-one?
(define one-to-one?
  (lambda (fun)
    (fun? (revrel fun))))

打赏