Kierra Gagnon
Kierra Gagnon

Reputation: 17

removing 0's from list in Racket

I am working on an assignment and in the function I am working on I need to remove all 0's from a list. So far I have the function removing all except for the first 0 from the list, I am hoping to receive some guidance as to how I can remove that first 0 as well.

(define (trimming list)
        (define thelist '())
            (begin (for-each
                       (lambda (x)
                            (if (member x thelist)
                                #t
                            (set! thelist (cons x thelist))))
                       list)
                   (reverse thelist)))
(trimming (list 0 0 1 3 0 5 0))

output:

'(0 1 3 5)

Upvotes: 0

Views: 162

Answers (1)

Shawn
Shawn

Reputation: 52579

Your posted code doesn't remove 0's from a list - it removes duplicates so that each element in the returned list is unique. It just so happens that your sample list only has duplicate 0's. It's also pretty unidiomatic - a more typical approach wouldn't use set! (You'd usualy just use remove-duplicates in Racket, or maybe something like (set->list (list->set your-list)) if you don't care about order).

The easy way to remove just 0's is to use filter-not:

(println (filter-not zero? '(0 0 1 3 0 5 0))) ; '(1 3 5)

If this is for an assignment, though, that probably doesn't meet the learning objectives. You do have the right general idea of building up a list of values to return; it just needs to be tweaked to do what you want instead of something else. A more idiomatic explicitly recursive skeleton using a named let might look like:

(define (remove-zeros list)
  (let loop ([list list] [result-list '()])
    (cond
      [(null? list) ; Base case; the input list has been fully processed and you're done
        (reverse result-list)] 
      [some-condition-to-skip-the-first-element-when-true? ; Write this bit yourself
        (loop (cdr list) result-list)] ; go on to the next element
      [else ; Add the first element to the result list; go on to the next
        (loop (cdr list) (cons (car list) result-list))])))

Upvotes: 1

Related Questions