Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kristianlm
Created February 1, 2017 09:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kristianlm/ae5c61c475f20d58321b045c903a95ad to your computer and use it in GitHub Desktop.
Save kristianlm/ae5c61c475f20d58321b045c903a95ad to your computer and use it in GitHub Desktop.
;; a nicer alist api
(define (aref alst key #!optional (missing (lambda () #f)) (= equal?))
(let loop ((alst alst))
(if (pair? alst)
(if (= (caar alst) key) (cdar alst) (loop (cdr alst)))
(if (procedure? missing) (missing) missing))))
(define (adel alst key #!optional (= equal?))
(alist-delete key alst =))
(define (aset alst key val #!optional (= equal?))
(alist-update key val alst =))
(define (ainc alst key proc #!optional (missing (lambda () '())) (= equal?))
(aset alst key (proc (aref alst key missing =)) =))
;; like map but give proc two arguments: the car and the cdr.
(define (amap alst proc)
(assert (procedure? proc))
(let loop ((alst alst) (result '()))
(if (pair? alst)
(loop (cdr alst)
(cons (proc (car (car alst))
(cdr (car alst)))
result))
(reverse result))))
;; ensure deterministic serialization of alst (useful when treated as
;; "hashmap")
(define (asort alst #!key
(key (lambda (a b) (string<= (conc a) (conc b))))
(val (lambda (x y) (string<= (conc x) (conc y)))))
(sort alst (lambda (a b) (if (equal? (car a) (car b))
(val (cdr a) (cdr b))
(key (car a) (car b))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment