寻找更简洁的方法从数字列表中创建关联列表

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

我正在寻找一个过程,它将采用 '(0 7 10 14) 形式的列表并将其转换为列表 '((0 . 7) (7 . 10) (10 . 14 )).下面的过程将完全做到这一点。我觉得比较乱,找不到更简单的写法。也许我可以使用内置的球拍功能来做到这一点?

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

使用 Racket,我们可以这样做:

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

它按预期工作:

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

也是这样。

  • map 相比,for/list 可以采用两个不同长度的列表 - 减少到最短的长度。

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