0

我是一个初学者,对方案有非常基本的了解,在理解如何解决一个练习方面有点麻烦。给定类似于以下结构的列表:

(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))

我在练习中遇到了很多麻烦,到目前为止,我只设法编写了一个程序来检查列表中是否存在国家名称并返回真/假:

(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)))

我不知道我应该从这里去哪里。任何帮助深表感谢。提前致谢。

4

1 回答 1

1

这个练习很容易用基本mapfilter、、和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))
于 2013-11-08T19:02:39.167 回答