;;; (boudin util) --- utility functions (define-library (boudin util) (import (scheme base) (scheme case-lambda) (scheme eval)) (export identity o constantly assoc-ref slurp eval/q intersperse string-intersperse) (begin (define (identity x) x) (define (o . procs) ; stole from chicken core (if (null? procs) identity (let loop ((procs procs)) (let ((h (car procs)) (t (cdr procs))) (if (null? t) h (lambda (x) (h ((loop t) x)))))))) (define (constantly x) (lambda _ x)) (define assoc-ref (case-lambda ((key alist) (assoc-ref alist key (lambda () (error "Unrecognized key." key)))) ((key alist failure) (cond ((assoc key alist) => cdr) (else (failure)))))) (define slurp (case-lambda (() (slurp (current-input-port))) ((port) (let loop ((ch (read-char)) (acc '())) (if (eof-object? ch) (list->string (reverse acc)) (loop (read-char) (cons ch acc))))))) (define (eval/q form env) ; this is probably a bad idea (eval (list 'quasiquote form) env)) (define (intersperse xs delim) (if (null? xs) '() (let loop ((acc (list (car xs))) (rest (cdr xs))) (if (null? rest) (reverse acc) (loop (cons (car rest) (cons delim acc)) (cdr rest)))))) (define (string-intersperse ss delim) (apply string-append (intersperse ss delim))) (define index (case-lambda ((xs needle) (index xs needle eq? (constantly #f))) ((xs needle comparator) (index xs needle comparator (constantly #f))) ((xs needle comparator fail) (let loop ((i 0) (xs xs)) (cond ((null? xs) (fail)) ((comparator (car xs) needle) i) (else (loop (+ i 1) (cdr xs)))))))) (define (string-index str ch) (index (string->list str) ch)) ))