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

Viewed 79

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))))))
3 Answers

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))
(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.

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))
Related