0
votes

I am Tasked (in exercise 8) with creating a function in Intermediate Student Language (Racket) that receives a list of numbers and a list of lists of numbers; each list is the same length. Name the first list breakpoints and the second LoR (list of rows). This function should be defined using map and should filter each row in LoR so that only numbers larger than that the n'th row in LoR only contains values larger than the n'th value in breakpoints-- here is an example for clarity:

(define breakpoints (list 7 2 15))

(define LoR (list (list 3 25 13) 
                  (list 1 2 11) 
                  (list 22 4 8)))

would output...

(list (list 25 13) (list 11) (list 22))

Doing this without using map would be fine and I understand the problem in that sense, but I am having trouble figuring out how to use map. I was thinking recursively in the sense that if the list of rows is not empty, I would cons the (filtered first row) to the (recursive call of the function using the rest of breakpoints and LoR) as so:

(define (parallel-filter breakpoints LoR)
  (cond((empty? breakpoints) empty)
       (else (cons ...
                   (parallel-filter (rest breakpoints) (rest LoR))))))

However, I'm not sure how to replace the ellipse with a map statement that would make the function work correctly-- as I understand, map's first parameter must be a one-parameter function and I'm not sure how to use map for this purpose. How do I proceed?

edited to correct output

1
I think that the whole point of the exercise is to use higher-order functions (map, filter, foldr, etc.) so you should not use explicit recursion to solve itÓscar López

1 Answers

2
votes

We can solve this problem by combining map and filter, but first bear in mind this:

  • You can't use just map, because it will always return a list of the same length as the original. For excluding some elements we must use filter (or alternatively: use foldr to implement our own version of filter)
  • map can receive more than one list as parameter, as long as its function receives enough parameters - one from each list
  • Your sample output is wrong for the first sublist

With all of the above in mind, here's one possible solution:

(define (parallel-filter breakpoints LoR)
  (map (lambda (brk lst) ; `brk` is from `breakpoints` and `lst` is from `LoR`
         (filter (lambda (ele) (> ele brk)) ; filter each sublist from `LoR`
                 lst))
       breakpoints
       LoR))

It works as expected:

(parallel-filter breakpoints LoR)
=> (list (list 25 13) (list 11) (list 22))