Skip to content

Instantly share code, notes, and snippets.

@kristianlm kristianlm/alst.scm

Created Feb 1, 2017
What would you like to do?
;; 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)))
(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
You can’t perform that action at this time.