;; make-shopper-card: name --> (command, any --> any) ;; (define make-shopper-card (local [(define most-recently-bought #f)] (lambda (name) (lambda (command some-item) (cond [(eq? command 'show-name) name] [(eq? command 'buy) (set! most-recently-bought some-item)] [(eq? command 'show-fave) most-recently-bought]))))) "make-shopper-card tests:" (define sw (make-shopper-card "sw")) (define jg (make-shopper-card "jg")) (sw 'show-name null) (jg 'show-name null) (sw 'show-fave null) (jg 'show-fave null) (sw 'buy "pizza") (sw 'show-fave null) (jg 'show-fave null) ;; this is a problem ;; make-shopper-card2: name --> (command, any --> any) ;; (define (make-shopper-card2 name) (local [(define most-recently-bought false)] (lambda (command some-item) (cond [(eq? command 'show-name) name] [(eq? command 'buy) (set! most-recently-bought some-item)] [(eq? command 'show-fave) most-recently-bought])))) "make-shopper-card2 tests:" (define sw2 (make-shopper-card2 "sw")) (define jg2 (make-shopper-card2 "jg")) (sw2 'show-name null) (jg2 'show-name null) (sw2 'show-fave null) (jg2 'show-fave null) (sw2 'buy "pizza") (sw2 'show-fave null) (jg2 'show-fave null) ;; fixed! ;;----------------- Alternative implementation --------------------------- ;; A shopping card is a structure with that holds three functions (lambdas): ;; getName returns the name associated with the card ;; buy will set the most recently bought item to the given string ;; getFave will return the most currently bought item ;; (make-shopcard ;; (lambda: --> string) ;; (lambda: string --> void) ;; (lambda: --> string)) (define-struct ShopCard (getName buy getFave)) ;; shopcardFac: string --> ShopCard ;; Factory for ShopCard that takes the ;; name string associated with the card ;; as an input. (define (shopcardFac name) (local [(define most-recently-bought false)] (make-ShopCard (lambda () name) (lambda (item) (set! most-recently-bought item)) (lambda () most-recently-bought)))) "ShopCard tests:" (define sw3 (shopcardFac "sw")) (define jg3 (shopcardFac "jg")) ((ShopCard-getName sw3)) ;; remember that getName returns a function,so it needs to be evaluated. ((ShopCard-getName jg3)) ((ShopCard-getFave sw3)) ((ShopCard-getFave jg3)) ((ShopCard-buy sw3) "pizza") ((ShopCard-getFave sw3)) ((ShopCard-getFave jg3))