Association Lists, Vectors, Bytevectors and Hash Tables
13.1 Association Lists
(define phone '((ana . "555-1234") (bo . "555-9876")))
(cdr (assq 'ana phone)) ; "555-1234"
(define (alist-update key val alist)
(cons (cons key val)
(filter (lambda (p) (not (eq? (car p) key))) alist))) ; SRFI-1 filter
(alist-update 'bo "555-0000" phone)13.2 Vectors
(define v (vector 1 2 3))
(vector-ref v 0) ; 1
(vector-set! v 0 99)
(vector-length v) ; 3
(make-vector 3 0) ; #(0 0 0)
#(1 2 3) ; literal (immutable)
(vector-map (lambda (x) (* x 2)) #(1 2 3)) ; #(2 4 6)
(vector-for-each display #(a b))
(vector-fill! (make-vector 3) 7)
(vector-copy #(1 2 3 4) 1 3) ; #(2 3)
(vector-append #(1) #(2 3)) ; #(1 2 3)
(vector->list #(1 2 3)) (list->vector '(1 2))
(vector->string #(#\a #\b)) ; "ab"13.3 Bytevectors
(define bv (bytevector 1 2 255))
(bytevector-u8-ref bv 2) ; 255
(bytevector-u8-set! bv 0 42)
(bytevector-length bv) ; 3
(make-bytevector 4 0)
(string->utf8 "λx") ; #u8(206 187 120)
(utf8->string (bytevector 72 105)) ; "Hi"
(bytevector-copy bv) (bytevector-append bv bv)13.4 Hash Tables
(make-hash-table), hash-set!, hash-ref, hash-for-each (+ SRFI-69)
(make-eq-hashtable), (make-hashtable equal-hash equal?), hashtable-set!, hashtable-ref
(make-hash), hash-set!, hash-ref, immutable (hash 'a 1) SRFI-69 built in
;; SRFI-69 (widely available; SRFI-125 is the newer API)
(import (srfi 69))
(define h (make-hash-table)) ; default equal? test
(hash-table-set! h 'ana 30)
(hash-table-set! h 'bo 25)
(hash-table-ref/default h 'ana 0) ; 30
(hash-table-ref/default h 'zed 0) ; 0
(hash-table-update!/default h 'ana (lambda (v) (+ v 1)) 0)
(hash-table-delete! h 'bo)
(hash-table-exists? h 'ana) ; #t
(hash-table-size h) ; 1 (number of entries)
(hash-table-walk h (lambda (k v) (display k) (display "=") (display v) (newline)))
(hash-table->alist h)
(hash-table-keys h) (hash-table-values h)
;; Word counting
(define (word-counts words)
(let ((t (make-hash-table)))
(for-each (lambda (w) (hash-table-update!/default t w (lambda (n) (+ n 1)) 0)) words)
(hash-table->alist t)))
(word-counts '(a b a c a)) ; ((a . 3) (b . 1) (c . 1)) (order may vary)