[英]How to update list of structs inside another struct in Racket (Universe)
[英]Racket list in struct
我刚开始用 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)))))
简短回答:使用递归遍历列表。 这看起来像家庭作业,所以我会给你一些提示; 填空:
(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
(*) 请注意,您已经知道如何编写此部分,只需使用访问该值的适当程序即可获取列表中第一项的价格!
有很多方法可以解决这个问题。 我提出的方法是遍历列表、对每个元素进行操作并递归组合结果的标准方法。
使用 foldl 和 map:
(foldl + 0
(map
(lambda (it)
(item-price it))
some-items))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.