返回表的函数:
下面是一个求工资的函数:
;;wage : number -> number
;; to compute the total wage (at $12 per hour) ;; of someone who worked forh
hours (define (wage h) (* 12 h))
显示,只能求单个人的工资,我们相求多个人的工资,于是想传入一个list过去:
;;hours->wages : list-of-numbers -> list-of-numbers
;; to create a list of weekly wages from a list of weekly hours (alon
) (define (hours->wages alon) ...)
我们希望函数返回一个list,里面的每个元素对应传入的时间。完整代码:
(define (wage h) (* 12 h)) ;hours->ages:list-of-numbers->list-of->numbers (define (hours->wages alon) (cond [(empty? alon) empty] [else (cons (wage (car alon)) (hours->wages (cdr alon)) )] )) (hours->wages (cons 480 (cons 336 empty)) )
输出:'(5760 4032)
包含结构体的表:
下面定义了一个库存记录inventory-record:
(define-struct ir (name price))
现在我们可以存储清单是下列2者之一:
1.empty
2.(cons ir inv) 其中ir是一条库存记录,inv是一个库存清单。
The simplest example of an inventory is empty
. To create a larger inventory, we must create an inventory record and cons
it onto another inventory:
(cons (make-ir 'doll 17.95) empty)
From here, we can create yet a larger inventory listing:
(cons (make-ir 'robot 22.05) (cons (make-ir 'doll 17.95) empty))
如何求所有库存的总价格。
(define-struct ir (name price)) (define (sum an-inv) (cond [(empty? an-inv) 0] [else (+ (ir-price (car an-inv)) (sum (cdr an-inv)))] )) (define x (cons (make-ir 'robot 22.05) (cons (make-ir 'doll 17.95) empty))) (sum x) ;output 40