Search code examples
schemeracketfold

How to add a list of two numbers using foldl/r in Racket/Scheme


I am trying to add two Lists of Two Structures using foldl/r, but I am not able to add the two Lists. I Have attached the Code below

(define-struct product-list (barcode expiry price ))
(define-struct tax-list (barcode tax))

(define (total-price products taxes)
(foldr 
+ (product-list-price products) (tax-list-tax taxes)))

(define products (list 
(make-product-list 1500 85)
(make-product-list 1501 30)
(make-product-list 1502 200)
(make-product-list 1503 15)
(make-product-list 1504 100)
))

(define taxes (list
(make-tax-list 1500 5)
(make-tax-list 1501 2)
(make-tax-list 1502 12)
(make-tax-list 1503 0)
(make-tax-list 1504 6)
))


Solution

  • Assuming that:

    • You want to add the prices and taxes element-wise on the two input lists
    • The products in the product list were correctly built (in your code they're missing the barcode)

    Then, you just need to extract the prices and taxes from the lists and add them together, like this:

    (define (total-price products taxes)
      (foldr
       +
       0
       (map product-list-price products)
       (map tax-list-tax taxes)))