3

我刚开始用 Racket 编程,现在我遇到了以下问题。我有一个带有列表的结构,我必须将列表中的所有价格加起来。

(define-struct item (name category price))
(define some-items
(list
   (make-item "Book1" 'Book 40.97)
   (make-item "Book2" 'Book 5.99)
   (make-item "Book3" 'Book 20.60)
   (make-item "Item" 'KitchenAccessory 2669.90)))

我知道我可以用:(item-price (first some-items))或返回价格(item-price (car some-items))

问题是,我不知道如何将所有商品的价格加起来。


对Óscar López的回答:我可能没有正确填写空白,但是当我按下开始时,Racket将代码标记为黑色并且不返回任何内容。

  (define (add-prices items)
  (if (null? items)           
     0                   
      (+ (first items)                 
         (add-prices (rest items)))))
4

2 回答 2

2

简短的回答:使用递归遍历列表。这看起来像家庭作业,所以我会给你一些提示;填空:

(define (add-prices items)
  (if (null? items)            ; if the list of items is empty
      <???>                    ; what's the price of an empty list?
      (+ <???>                 ; else add the price of the first item (*)
         (add-prices <???>)))) ; with the prices of the rest of the list

(*) 请注意,您已经知道如何编写这部分,只需使用适当的程序获取列表中第一项的价格以获取值!

有很多方法可以解决这个问题。我建议的是遍历列表的标准方法,对每个元素进行操作并递归组合结果。

于 2012-11-07T19:38:51.527 回答
1

使用 foldl 和地图:

(foldl + 0
       (map 
         (lambda (it)
           (item-price it))
             some-items))
于 2012-11-11T02:31:46.237 回答