X-Git-Url: http://www.chiark.greenend.org.uk/ucgi/~mdw/git/fringe/blobdiff_plain/652d4a587e0ab95a9673ca1c8fd6f109a0df6a25..8a4f4f075a6e2e90039b172242097a4eca48d60b:/scheme-fringe.scm diff --git a/scheme-fringe.scm b/scheme-fringe.scm index 0dc93df..47b1266 100644 --- a/scheme-fringe.scm +++ b/scheme-fringe.scm @@ -3,8 +3,6 @@ ;;; Scheme implementation of a `same-fringe' solver. Assumes Chicken, but ;;; should port easily. -(use syntax-case) ; Chicken-specfic - ;;;-------------------------------------------------------------------------- ;;; Utilities. @@ -76,8 +74,8 @@ ((define-generator (name . args) . body) (define (name . args) (make-coroutine (lambda () - (begin . body) - (resume (calling-coroutine) #f #f))))))) + (begin . body) + (resume (calling-coroutine) #f #f))))))) (define (yield object) ;; Yield OBJECT from a generator. The generator protocol returns two @@ -86,14 +84,23 @@ (with-values () (resume (calling-coroutine) object #t) #f)) +(define (reduce-generator func init gen) + ;; Call FUNC for each item in the generator GEN. + ;; + ;; We maintain a STATE, which is initially INIT. For each ITEM produced by + ;; the generator, we replace the state by (FUNC ITEM STATE); finally, we + ;; return the final state. + + (let loop ((state init)) + (with-values (item any?) (resume gen) + (if any? + (loop (func item state)) + state)))) + (define (list-generator gen) ;; Collect the elements generated by GEN into a list and return it. - (let loop ((l '())) - (with-values (it any?) (resume gen) - (if any? - (loop (cons it l)) - (reverse l))))) + (reverse (reduce-generator cons '() gen))) (define (same-generators? gen-a gen-b) ;; Return whether GEN-A and GEN-B generate the same elements in the same @@ -161,9 +168,8 @@ (define (main args) (cond ((null? args) (error "bad args")) ((null? (cdr args)) - (do ((l (list-generator (fringe (parse-tree (car args)))) (cdr l))) - ((null? l)) - (write-char (car l))) + (reduce-generator (lambda (ch ?) (write-char ch)) #f + (fringe (parse-tree (car args)))) (newline)) ((null? (cddr args)) (display (if (same-generators? (fringe (parse-tree (car args)))