How to make two lists, one with even numbers and one with odd numbers, in scheme?

StackOverflow https://stackoverflow.com/questions/23571303

  •  19-07-2023
  •  | 
  •  

Question

I have a problem.

For example:

We have one unsorted list:

(1 4 5 3 6 7)

Can you help me make 2 lists?

One odd numbered, increasing list:

(1 3 5 7)

and the other even numbered, decreasing list:

(6 4)

Don't use sort!

Was it helpful?

Solution

(define (split filter lst)
  (let loop ((a '()) (b  '()) (lst lst))
    (if (null? lst)
        (values a b)
        (let ((cur (car lst)))
          (if (filter cur)
              (loop (cons cur a) b (cdr lst))
              (loop a (cons cur b) (cdr lst)))))))

(split odd? '(1 2 3 4 5 6 7 8 9 10))
; ==> (9 7 5 3 1), (10 8 6 4 2)

Now, to make one that separates odds from evens and in a specific order would be simple.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top