TomatoFarmer
TomatoFarmer

Reputation: 473

Looking for cleaner way to make association list out of list of numbers

I'm looking to write a procedure that will take a list in the form '(0 7 10 14) and transform it into a list '((0 . 7) (7 . 10) (10 . 14)). The procedure below will do exactly that. I think it's rather messy and can't find a simpler way to write it. Maybe I can use a built-in racket function to do this?

(define (simplify-path path)
    (if (null? (cddr path))
        (cons (cons (car path) (cadr path)) '())
        (begin (cons (cons (car path) (cadr path))
                     (simplify-path (cdr path))))))

Upvotes: 2

Views: 88

Answers (3)

alinsoar
alinsoar

Reputation: 15793

written in mit-scheme.

(define list->assocs
  (lambda (l)
    (define pair-first-second
      (lambda (l)
        (cons (car l) (cadr l))))
    (define iter
      (lambda (l k)
        (if (eq? '() (cddr l))
            (k (pair-first-second l))
            (iter (cdr l)
                  (lambda (r)
                    (k (cons (pair-first-second l) r)))))))
    (if (or (eq? '() l)
            (eq? '() (cdr l)))
        l
        (iter l
              (lambda (x) x)))))


(list->assocs '(0 7 10 14))

Upvotes: 1

Gwang-Jin Kim
Gwang-Jin Kim

Reputation: 9865

(define (simplify-path path)
  (for/list ([x path] [y (cdr path)]) (cons x y)))

Does it too.

  • In contrast to map, for/list can take two different length lists - cuts down to length of shortest.

Upvotes: 1

Óscar López
Óscar López

Reputation: 236004

Using Racket, we can do this:

(define (simplify-path path)
  (map cons
       (drop-right path 1)
       (rest path)))

It works as expected:

(simplify-path '(0 7 10 14))
=> '((0 . 7) (7 . 10) (10 . 14))

Upvotes: 1

Related Questions