我是初学者,对计划有非常基础的知识,并且在理解如何解决练习方面有点麻烦。给出类似于以下结构列表:
(define-struct swimmer (name country time))
(define list-swimmers
(list
(make-swimmer "Hans" 'Germany 187.34)
(make-swimmer "Fred" 'USA 209.12)
(make-swimmer "Bianca" 'France 192.01)
(make-swimmer "Adolf" 'Germany 186.79)
我必须创建一个消耗国家名称和名单名称的程序,并从该国家的每个游泳运动员中获得最佳时间,并使用另一个消耗国家名单并与国家产生结果的程序,然后是最佳时间,即
(listof swimmer) (listof symbol) -> (listof (list symbol number))
我在练习中遇到了很多麻烦,到目前为止只设法编写了一个程序来检查列表中是否存在国家名称并返回true / false:
(define (contains-country? c a-list-of-swimmers)
(cond
[(empty? a-list-of-swimmers) false]
[(cons? a-list-of-swimmers)
(cond
[(symbol=? (swimmer-country (first a-list-of-swimmers))c) true]
[else
(contains-country? c (rest a-list-of-swimmers))])]))
(define (best-time-by-country (contains-country? c a-list-of-swimmers)))
我不清楚我应该从哪里开始。任何帮助深表感谢。提前谢谢。
答案 0 :(得分:1)
使用基本map
,filter
和apply
程序很容易解决此练习:
(define (best-of slist country)
(apply min ; take the minimum
(map swimmer-time ; of the times
(filter ; from every entry from the selected country
(lambda (s) (eq? country (swimmer-country s)))
slist))))
(best-of list-swimmers 'Germany)
=> 186.79
并且在此基础上:
(define (best-of-list slist countries)
(map
(lambda (c) (list c (best-of slist c)))
countries))
(best-of-list list-swimmers '(USA France))
=> '((USA 209.12) (France 192.01))
修改强>
鉴于您需要使用我不熟悉的Racket中的“使用列表缩写的初学者”语言,我已经浏览了相关的文档并提出了这个问题;我希望这与你所教的内容一致:
(define (best-of-helper slist country max-value)
(if (null? slist)
max-value
(if (eq? country (swimmer-country (car slist)))
(best-of-helper (cdr slist)
country
(if (number? max-value)
(min max-value (swimmer-time (car slist)))
(swimmer-time (car slist))))
(best-of-helper (cdr slist) country max-value))))
(define (best-of slist country)
(best-of-helper slist country #f))
(best-of list-swimmers 'Germany)
=> 186.79
和
(define (best-of-list slist countries)
(if (null? countries)
'()
(cons
(list (car countries) (best-of slist (car countries)))
(best-of-list slist (cdr countries)))))
(best-of-list list-swimmers '(USA France))
=> (list (list 'USA 209.12) (list 'France 192.01))