Fernando Gardeazabal
Fernando Gardeazabal

Reputation: 101

How to work with specific range of numbers in lists in scheme?

I'm learning scheme and I would like to know how to remove, for example the negative numbers of a list so I can work with the positives, until now I only got # instead of removing the negatives. Here is my code:

 (define test
    (lambda (list)
      (map (lambda (x) (if (> x 0) x ))list)))

Upvotes: 1

Views: 443

Answers (3)

user448810
user448810

Reputation: 17876

Here is the standard version of filter:

(define (filter pred? xs)
  (let loop ((xs xs) (ys '()))
    (cond ((null? xs) (reverse ys))
          ((pred? (car xs))
            (loop (cdr xs) (cons (car xs) ys)))
          (else (loop (cdr xs) ys)))))

With that, you can build a new list containing only the positive values of the input list:

> (filter positive? '(3 9 -2 4 0 -1 7))
(3 9 4 7)

You might enjoy my blog, which provides lots of Scheme code for you to study.

Upvotes: 2

Penguin_
Penguin_

Reputation: 21

You will need to disect and rebuild the list element by element. This is a very common recursive pattern in Scheme and should be covered in depth in your course material.

(define (filter list pred)
  (cond ((null? list)
          '())
        ((pred (car list))
          (filter (cdr list) pred))
        (else
          (cons (car list) (filter (cdr list) pred)))))

Upvotes: 1

Fernando Gardeazabal
Fernando Gardeazabal

Reputation: 101

I turned the negatives of the list into 0 so it doesn't affect what I do.

Here's the code for it:

 (define test
   (lambda(list)
        (map (lambda (x)(if (> x  0) x
                    0 ))list)  ) )

Upvotes: 1

Related Questions