Reputation: 29
If I have a list of number, how can I remove the smallest number of the list and make a new list. I have only seen how to get the max number of the list. I am not sure how to remove the min number.
(check-expect (drop-lowest (list 3 4 5))
(list 4 5))
(define (drop-lowest lon)
(cond
[(empty? lon) #false]
[(cons? lon)
(min
(first lon)
(drop-lowest (rest lon)))]))
Upvotes: 0
Views: 246
Reputation: 66459
Your code says that you can remove the smallest element from '(1)
with (min 1 #false)
, which clearly can't be the case.
Removing the smallest element from the empty list is not #false
, it is the empty list.
Also, you can't remove the smallest element from a list by taking the minimum of its first element (which is a number) and the list you get by removing the smallest element from its tail (which should be a list).
You can't do this conveniently with a single function - you can't know whether the first element is the smallest unless you have already examined all the other elements, and repeatedly looking for the minimum is very wasteful.
Break it down into three functions; one finds the minimum value, one removes a specific value, and the third just uses the first two:
(define (drop-lowest lon)
(remove (minimum lon) lon)))
Implementing, or finding, the required functions left as an exercise.
Upvotes: 0
Reputation: 52579
The argmin
and remove
functions make it easy:
#lang racket
(define (drop-lowest lst)
(remove (argmin identity lst) lst =))
(writeln (drop-lowest '(3 4 5))) ; '(4 5)
argmin
returns the minimum element of a list as transformed by a function (identity
to return the element itself in this case), and remove
removes the first element of the list that is its second argument that compares equal to its first argument. If you want to remove all occurances of the minimum value instead of just the first, use remove*
instead.
Upvotes: 1