Reputation: 33
I just started programming with Racket and now I have the following problem. I have a struct with a list and I have to add up all prices in the list.
(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)))
I know that I can return the price with: (item-price (first some-items))
or (item-price (car some-items))
.
The problem is, that I dont know how I can add up all Items prices with this.
Answer to Óscar López: May i filled the blanks not correctly, but Racket mark the code black when I press start and don't return anything.
(define (add-prices items)
(if (null? items)
0
(+ (first items)
(add-prices (rest items)))))
Upvotes: 3
Views: 3907
Reputation: 379
use foldl and map:
(foldl + 0
(map
(lambda (it)
(item-price it))
some-items))
Upvotes: 1
Reputation: 236170
Short answer: traverse the list using recursion. This looks like homework, so I'll give you some hints; fill-in the blanks:
(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
(*) Notice that you already know how to write this part, simply get the price of the first item in the list using the appropriate procedures for accessing the value!
There are many ways to solve this problem. The one I'm proposing is the standard way to traverse a list, operating over each of the elements and recursively combining the results.
Upvotes: 2