Created
February 26, 2011 14:12
Some examples with "yield" generators in scheme.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(define (generate tree) | |
(let ((jump null)) | |
(lambda () | |
(if (null? jump) | |
(call/cc | |
(lambda (yield) | |
(let loop ((stack (list tree))) | |
(cond | |
((null? stack) null) | |
(else | |
(call/cc | |
(lambda (k) | |
(set! jump k) | |
(yield (node-value (car stack))))) | |
(loop (append (filter (lambda (el) (not (null? el))) | |
(children (car stack))) | |
(cdr stack)))))))) | |
(jump))))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(define (iterate callback tree) | |
(let loop ((values '()) | |
(stack (list tree))) | |
(cond | |
((null? stack) values) | |
(else | |
(loop (cons (callback (node-value (car stack))) | |
values) | |
(append (filter (lambda (el) (not (null? el))) | |
(children (car stack))) | |
(cdr stack))))))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(define (make-node val . others) | |
(case (length others) | |
((0) (list val null null)) | |
((1) (list val (car others) null)) | |
((2) (list val (car others) (cadr others))))) | |
(define (node-value node) | |
(car node)) | |
(define (node-left node) | |
(cadr node)) | |
(define (node-right node) | |
(caddr node)) | |
(define (children node) | |
(cdr node)) | |
(define *example* | |
(make-node 3 | |
(make-node 4) | |
(make-node 2 | |
(make-node 1) | |
(make-node 0 | |
'() | |
(make-node -1))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment