Search code examples
schemerackethtdp

Idiomatic usage of filter, map, build-list and local functions in Racket/Scheme?


I'm working through Exercise 21.2.3 of HtDP on my own and was wondering if this is idiomatic usage of the various functions. This is what I have so far:

(define-struct ir (name price))
(define list-of-toys (list
                      (make-ir 'doll 10)
                      (make-ir 'robot 15)
                      (make-ir 'ty 21)
                      (make-ir 'cube 9)))

;; helper function
(define (price< p toy)
  (cond
    [(< (ir-price toy) p) toy]
    [else empty]))

(define (eliminate-exp ua lot)
  (cond
    [(empty? lot) empty]
    [else
     (filter ir? (map price< (build-list (length lot)
                                         (local ((define (f x) ua)) f)) lot))]))

To my novice eyes, that seems pretty ugly because I have to define a local function to get build-list to work, since map requires two lists of equal length. Can this be improved for readability? Thank you.


Solution

  • You could implement eliminate-exp with filter alone:

    (define (eliminate-exp ua lot)
      (define (price< toy) (< (ir-price toy) ua))
      (filter price< lot))