简体   繁体   中英

Racket list in struct

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

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.

use foldl and map:

(foldl + 0
       (map 
         (lambda (it)
           (item-price it))
             some-items))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM