企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] ## 习题 10.1.8 设计求解二次方程的函数 quadratic-roots,该函数的输入为方程的系数,即a、b以及c,所执行的计算根据输入而定 ``` (define (base-root a b c) (sqrt (- (* b b) (* 4 a c)))) (define (root-add a b c) (/ (+ (- b) (base-root a b c)) (* 2 a))) (define (root-desc a b c) (/ (- (- b) (base-root a b c)) (* 2 a))) (define (quadratic-roots a b c) (cond [(= a 0) 'degenrate] [(< (* b b) (* 4 a c)) 'none] [(= (* b b) (* 4 a c)) (/ (- b) (* 2 a))] [(> (* b b) (* 4 a c)) (cons (root-add a b c) (cons (root-desc a b c) empty))])) ;(quadratic-roots 1 2 1) ;-1 ;(quadratic-roots 3 4 5) ;'none (quadratic-roots 3 40 5) ;'(-0.1261943765504725 -13.207138956782861) ``` ## 习题 10.1.9 在许多杂货店,收银员需要向顾客报出价格。收银员的计算机对于顾客必须支付的金额,构造含有如下五个元素的表 1.元的数额; 2.如果元的数额是1,这一元素是符号 'dollar,否则就是 'dollars 3.符号and; 4.分的数额; 5.如果分的数额是1,这一元素是符号cent,否则就是'cents。 开发函数 controller,该函数读入一个数,返回如上描述的表。例如,如果金额数是$1.03,那么`( controller 103)`的计算过程如下: ``` (controller 103) ;;预期值 ;;(cons 1 (cons dollar (cons and (cons 3(cons cents empty)))) ``` 提示: Scheme提供了算术操作 quotient和 remainder,对于整数n和m,分别生成n/m的商和余数。 解答 ``` ; 通过美元价格输出 cons ; 模板 ;(define (controller price) ; (cons 美元 ; (cons ('dollar 或 'dollars) ; (cons 'and ; (cons 美分 ; (cons ('cent 或 'cents) empty)))) ;预期 ;(cons 1 (cons dollar (cons and (cons 3 (cons cents empty))))) (define (controller money) (cons (quotient money 100) (cons (cond[(= (quotient money 100) 1) 'dollar] [else 'dollars]) (cons 'and (cons (remainder money 100) (cons (cond[(= (remainder money 100) 1) 'cent] [else 'cents]) empty)))))) (controller 230) ;(list 2 'dollars 'and 30 'cents) (controller 101) ;(list 1 'dollar 'and 1 'cent) ``` ## 习题 10.2.2 给出包含每个物品照片的库存清单的数据定义和结构体定义。说明如何表示图103所示的库存清单。 设计函数 show-picture,该函数读入一个符号(玩具的名字)和一个上述定义的库存清单,函数返回相应的玩具照片,如果库存清单中没有此种玩具,返回 false。 ![D05015CE-B155-436F-9C6B-738E77D9D612.png](http://yanxuan.nosdn.127.net/651d7930199a52486d0ef45be656c2ee.png) 解答: ``` ; 设置物品的结构体 (define-struct goods (name price pictrue)) ; 通过物品名称获取物品照片 (define (shop-symbol? name list-struct) (cond [(empty? list-struct) false] [(symbol=? name (goods-name (first list-struct))) (goods-pictrue (first list-struct))] [else (shop-symbol? name (rest list-struct)) ] )) ;初始化商店物品 (define list-goods (cons (make-goods 'robot 29.95 'robot-p) (cons (make-goods 'doll 11.95 'doll-p) (cons (make-goods 'rocket 19.95 'rocket-p) empty)))) (shop-symbol? 'robot list-goods ) ;'robot-p (shop-symbol? 'robot empty) ;#flase ```