Im trying to write a small program that will take a list as an input and the first function is supposed to remove values that are greater than 4 and the other one is supposed to remove values that are lower than 4 in the check-expects. I figure this is a simple solution but I cant seem to figure it out as Im still new to lists and data structures. Any help would be appreciated, here is the code:
(define (removehigher lon n)
(cond [(> n lon)(remove (lon))]
[(< n lon) true]))
(define (removelower lon n)
(cond [(> n lon) true]
[(< n lon) (remove(lon))]))
(check-expect(removehigher(list 0 1 2 3 4 5 6)4)(list 0 1 2 3))
(check-expect(removelower(list 0 1 2 5 6 7) 3)(list 5 6 7))
CodePudding user response:
There is a function called filter
which would do this.
(define (my-filter pred lst (acc '()))
(cond [(null? lst) (reverse acc)]
[(pred (car lst)) (my-filter pred (cdr lst) (cons (car lst) acc))]
[else (my-filter pred (cdr lst) acc)]))
It is actually an in-built function filter
. I use my-
as prefix to not to overwrite this in-built function.
Once you have the function filter
(or my-filter
), you can write your desired functions easily - it is then about to define the predicate function (pred
) correctly for each of the cases:
(define (remove-higher lst n)
(filter (lambda (x) (<= x n)) lst))
(define (remove-lower lst n)
(filter (lambda (x) (<= n x)) lst))
Alternatively, one could also use append-map
:
(define (remove-higher lst n)
(append-map (lambda (x) (if (<= x n) (list x) '())) lst))
(define (remove-lower lst n)
(append-map (lambda (x) (if (<= n x) (list x) '())) lst))
Or define filter
using append-map
:
(define (my-filter pred lst)
(append-map (lambda (x) (if (pred x) (list x) '())) lst))
append-map
in turn can be defined:
(define (my-append-map func lst)
(apply append (map func lst)))