🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## 由n个 hello构成的表 下面设计函数 hellos,该函数以自然数n为参数,输出为由n个 hello构成的表,该函数的合约为: ``` ;由n个 hello构成的表 ;hellos:n->list-of-symbols ;预期值 ;(hellos 0) ;empty ;(hellos 1) ;(cons 'hello empty) ->(cons 'hello (hellos 0)) ;可以看出带有递归性 ; (hellos 2) ; (cons 'hello (cons 'hello empty)) -> (cons 'hello (hellos 1)) (define (hellos n) (cond [(= n 0) empty] [else (cons 'hello (hellos (- n 1)))])) (hellos 2) ;(list 'hello 'hello) ``` ## 11.2.1 把 hellos一般化为 repeat,该函数读入自然数n和一个符号,返回包含n个符号的表。 ``` (define (repeat sym n) (cond [(= n 0) empty] [else (cons sym (repeat sym (- n 1)))])) (repeat 'hello 3) ; (list 'hello 'hello 'hello) ``` ## 11.2.2 设计函数 tabulate-f,把函数f应用于一些由自然数值组成的表,其中f是 ``` ;; f:number->number (define (f x) (+ (* 3 (* x x)) (+ (* -6 x)) -1)) ``` 具体地说,函数读入自然数n,返回由n个posn结构体组成的表,表的第一个元素是点`n (f n)`,第二个元素是点`(n-1 (f n-1))`,以此类推。 解答 ``` ;(f 0) ;-1 ;(f 1) ;-4 (define (f x) (+ (* 3 (* x x)) (+ (* -6 x)) -1)) ;tabulate-f: n-> (cons (n fn) (cons (n-1 (f n-1)))) ;0 -> empty ;1 -> (cons (1 (f 1) empty)) -> (cons (1 (f 1) (tabulate-f 0))) ;2 -> (cons (2 (f 2) (cons (1 (f 1)) empty))) ->(cons (2 (f 2) (tabulate-f 1) )) (define (tabulate-f n) (cond [(= n 0) empty] [(= n 1) (cons (make-posn 1 (f 1)) empty)] [else (cons (make-posn n (f n)) (tabulate-f (- n 1)))])) ;(tabulate-f 0) ;'() ;(tabulate-f 1) ;(list (make-posn 1 -4)) (tabulate-f 2) ;(list (make-posn 2 -1) (make-posn 1 -4)) ``` ## 11.4.3 设计 product-from-minus-11这个函数读入一个大于或等于-11的整数n,返回在-11(不包括)和n(包括)之间所有数的乘积。 解答 ``` ;product-from-minus-11:number->number ; -11 -> 1 ; -10 -> -10*1 ; -9 -> -9*-10 ; -8 -> -8*-10*-9 - > -8 * (product-from-minus-11 -9 ) ; -n -> n * (product-from-minus-11 (- n 1) ) (define (product-from-minus-11 n) (cond [(= n -11) 1] [else (* n (product-from-minus-11 (- n 1)))])) ;(product-from-minus-11 -11) ;-1 (product-from-minus-11 -10) ;-10 ``` ## 11.5.2 定义函数 multiply,其输入是两个自然数n和x,不使用 Scheme提供的*,返回n*x。最后,去除这些定义之中的+。 提示:n乘以x就是把n个x加起来。 解体 ``` ;; multiply:number,number->number ;; 0,2->0 ;; 1,2->1*2 ;; 2,2->2*2 ;; 3,3->2*2*2->2*(multiply 2 2) ;; n,x->x*(multiply (- n 1) x) (define (multiply n x) (cond [(= n 0)0] [(= n 1)x] [else (* x (multiply (- n 1) x))])) (multiply 0 2);0 (multiply 1 2);2 (multiply 3 2);8 ```