user1922
user1922

Reputation: 51

Create list such that the min is separated from the list recursively in scheme?

i need to create a list such that the min is always at the outside in a list.

Example

input (1 2 3)

output (1 (2 3))

Here is my code, assuming that the numbers are in descending order, which i wish to extent later to a general case.

I am getting an unexpected output of (3 2 1 0 -1 -2 -3 ()).

How do I achieve this in scheme any ideas?'

(define (find-min-rest L) (if (null? (cdr L)) (let ( (x (car L))) (cons x '( ()))) (let* ((ret-ans (find-min-rest (cdr L))) (cur-elem (car L)) (mini (car ret-ans)) (rem-list (cdr ret-ans))) (cond ((> cur-elem mini) (cons cur-elem (cons mini rem-list)))))))

Upvotes: 1

Views: 181

Answers (2)

Óscar López
Óscar López

Reputation: 236140

It'll be simpler if you use built-in procedures, and split the problem in parts. Notice that the following assumes that there's a single minimum, adjust as necessary:

(define (find-min-rest L)
  (let* ((the-min  (apply min L))
         (the-rest (remove the-min L)))
    (list the-min the-rest)))

(find-min-rest '(1 2 3))
=> '(1 (2 3))

Upvotes: 0

user1922
user1922

Reputation: 51

The code

(define (find-min-rest L)
    (if (null? (cdr L)) (let ( (x (car L))) (cons x '( ())))
        (let* ((ret-ans (find-min-rest (cdr L))) (cur-elem (car L)) (mini (car ret-ans)) (rem-list (cdr ret-ans)))
          (cond ((> cur-elem mini)  (cons cur-elem (cons mini rem-list)))))))

Upvotes: 0

Related Questions