Skip to content

Instantly share code, notes, and snippets.

@Idorobots
Created February 8, 2021 15:41
Show Gist options
  • Save Idorobots/60968dcbbcd3b0779c146f77acbe29af to your computer and use it in GitHub Desktop.
Save Idorobots/60968dcbbcd3b0779c146f77acbe29af to your computer and use it in GitHub Desktop.
Some stream-based continuation whatever I wrote a year ago and just only now found unfinished. 🤷
;; Stream Returning Converter
;; Assumes syntax & macro-expanded code.
(load "compiler/ast.scm")
(load "compiler/utils.scm")
(define (src expr source)
(cond ((define? expr) (src-define expr source))
((lambda? expr) (src-lambda expr source))
((if? expr) (src-if expr source))
((symbol? expr) (src-source expr source))
((number? expr) (src-source expr source))
((null? expr) (src-source expr source))
('else (src-application expr source))))
(define (src-source expr source)
(if (empty? source)
`(source-single ,expr)
`(map-stream (lambda _ ,expr)
,source)))
(define (src-define expr _)
(make-val-define (define-name expr)
(src (define-value expr) '())))
(define (src-lambda expr _)
(let ((arg (gensym 'arg))
(args (lambda-args expr)))
`(flat-flow
(lambda (,arg)
(apply (lambda ,args
,(src (lambda-body expr) '()))
,arg)))))
(define (src-if expr source)
(let ((c (if-predicate expr))
(t (if-then expr))
(e (if-else expr)))
`(phi-stream ,(src c source)
(lambda (source)
,(src t '(filter-stream true? source)))
(lambda (source)
,(src e '(filter-stream false? source))))))
(define (src-application expr source)
(let ((op (app-op expr))
(args (app-args expr)))
`(via ,(src-application-args (reverse args) '()) ,op)))
(define (src-application-args args acc)
(if (empty? args)
(src-source (cons 'list acc) '())
(let ((v (gensym 'value)))
`(flat-map-stream (lambda (,v)
,(src-application-args (cdr args) (cons v acc)))
,(src (car args) '())))))
;; Tests
(define stream= (flow (curry apply =)))
(define stream* (flow (curry apply *)))
(define stream- (flow (curry apply -)))
(define factorial
(lambda (n)
(if (stream= n 0)
1
(stream* n (factorial (stream- n 1))))))
(define factorial
(lambda (n cont)
(cont= n
0
(lambda (v1) ;continuation
(if v1
(cont 1)
(cont- n
1
(lambda (v2) ;continuation
(factorial v2
(lambda (v3) ;continuation
(cont* n
v3
cont))))))))))
(define stream-map (flip map-stream))
(define stream-filter (flip filter-stream))
(define (lambda-flow f)
(flat-flow (lambda (args)
(apply f args))))
(define factorial
(lambda-flow
(lambda (n)
(-> (source-single (list n 0))
(via stream=)
(phi-stream (lambda (source)
(-> source
(stream-filter true?)
(stream-map (lambda _ 1))))
(lambda (source)
(-> source
(stream-filter false?)
(stream-map (lambda _ (list n 1)))
(via stream-)
(stream-map list)
(via factorial)
(stream-map (curry list n))
(via stream*))))))))
(-> (source-single (list 23))
(via factorial)
(run-with (sink println)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment