【问题标题】:Return lowest number contained in structures with an identical parameter返回具有相同参数的结构中包含的最小数字
【发布时间】:2013-11-08 16:57:39
【问题描述】:

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

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

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

【问题讨论】:

  • 定义runner 结构如何让你调用make-swimmer
  • 糟糕,这是我使用的模板的剩余部分。谢谢指出,我编辑了。

标签: scheme racket


【解决方案1】:

使用基本的mapfilterapply 程序很容易解决这个练习:

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

【讨论】:

  • 非常感谢您提供解决方案。虽然它似乎有效,但恐怕它正在使用我们课程中尚未涵盖的功能。我们被指示使用带有列表缩写的初学者作为选择的语言,如果这敲响了任何铃声。看来我们必须使用更原始的方法来解决问题,因为需要定义诸如apply之类的函数。
猜你喜欢
  • 1970-01-01
  • 2012-02-05
  • 1970-01-01
  • 2019-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多