Skip to content

Instantly share code, notes, and snippets.

@dcalacci
Created September 29, 2012 03:29
Show Gist options
  • Save dcalacci/3803058 to your computer and use it in GitHub Desktop.
Save dcalacci/3803058 to your computer and use it in GitHub Desktop.
a racket script to determine how much a given person owes for groceries
;; a shopping trip is a
;; (make-shopping-trip string lon lon lon)
;; where name is the name of the trip
;; a is the list of items andrea should pay for
;; dj is the list of items dan and jansen should pay for
;; all is the list of items everyone should pay for
;; paid is the person who paid for the food
;;(not actually lists of items, rather, lists of prices)
(define-struct shopping-trip (name a dj all paid))
(define 9-24-shaws
(make-shopping-trip
"9-24-shaws"
'()
(list 4.59)
(list 1.59 3.19 3.29 1.69 -.20 -.30 2.59 2.69)
"dan"))
(define 9-24-tjs
(make-shopping-trip
"9-24-tjs"
(list 3.29 1.79 1.49 1.99 2.07 1.69 1.69 2.69)
(list 1.38 2.49 3.99)
(list 2.29 2.99 1.99 0.57 2.99 2.49 1.69 2.29 0.79 1.99
2.99 0.79 2.29 2.29 0.79 0.79 0.79 1.29 2.99 2.99 1.19)
"dan"))
(define 9-16-shaws
(make-shopping-trip
"9-16-shaws"
(list 1.49 0.93 -.50)
(list 0.99 1.75 -.11 4.59 5.79)
(list 2.49 3.59 2.69 1.49)
"andrea"))
(define 9-14-tjs
(make-shopping-trip
"9-14-tjs"
'()
'()
(list 1.99 3.79 0.99 1.29 0.76 3.49 1.99 1.39
1.29 2.29 1.49 0.79 3.69 2.79)
"andrea"))
(define 9-14-shaws
(make-shopping-trip
"9-14-shaws"
(list 3.99 2.19 3.19 3.99 3.43 -.98 -1.74 -.69 8.39 -1.90)
(list 3.29)
(list 1.39 2.59 2.25 2.49 2.75 2.39 3.19 -.51)
"andrea"))
(define trips (list
9-24-shaws
9-24-tjs
9-16-shaws
9-14-tjs
9-14-shaws))
;; person-trips : String, [ListOf Trips] -> [ListOf Trips]
;; returns a list of trips where the given person paid
(define (person-trips name lot)
(filter (λ (t) (string=? (shopping-trip-paid t) name))
lot))
(define andrea-trips (person-trips "andrea" trips))
(define dan-trips (person-trips "dan" trips))
;; person-owes : String, [Listof Trips] -> Number
;; returns the amount the givern person owes from all the given shopping trips
(define (person-owes name los)
(foldr + 0
(foldr
(λ (trip l)
(append (cond
[(string=? name "andrea")
(shopping-trip-a trip)]
[else (list (/ (foldr + 0 (shopping-trip-dj trip)) 2))])
(list (/ (foldr + 0 (shopping-trip-all trip)) 3))
l))
'()
los)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment