Skip to content

Instantly share code, notes, and snippets.

@lehitoskin
Created July 16, 2017 21:04
Show Gist options
  • Save lehitoskin/8e146e03060bbb00e3e8cbff45e57b20 to your computer and use it in GitHub Desktop.
Save lehitoskin/8e146e03060bbb00e3e8cbff45e57b20 to your computer and use it in GitHub Desktop.
nested let to nested lambdas
(define (last lst)
(if (null? lst)
null
(if (null? (cdr lst))
(car lst)
(last (cdr lst)))))
; nested-lets->combination
; expected result:
; '((λ (a)
; ((λ (b) ((λ (a) ((λ (c) ((λ (d) (display a) (newline) (display b) (newline) (display c) (newline) (display d) (newline)) (+ c 4))) (+ b 3))) (+ 1 1)))
; (+ a 2)))
; (+ 1 1))
(let ((let? (λ (exp) (eq? (car exp) 'let)))
(let-assocs (λ (exp) (cadr exp)))
(let-body (λ (exp) (cddr exp)))
(make-lambda (λ (parameters body) (cons 'λ (cons parameters body))))
(nested '(let ((a (+ 1 1)))
(let ((b (+ a 2)))
(let ((c (+ b 3)))
(let ((d (+ c 4)))
(display a)
(newline)
(display b)
(newline)
(display c)
(newline)
(display d)
(newline)))))))
(let loop ((b (car (let-body nested))))
(define assocs (let-assocs b))
(define vars
(if (null? assocs)
null
(map car assocs)))
(define exps
(cond
; empty associations
((null? assocs) null)
; only one association
((null? (cdr assocs)) (car assocs))
; malformed let
((not (pair? (cadr assocs)))
(error "Malformed let associations -- NESTED-LETS->COMBINATION" assocs))
(else (map cadr assocs))))
(define exp (last exps))
(cond ((let? (last b))
(define top-var (caar (let-assocs nested)))
(list (make-lambda (list top-var)
(cons (list (make-lambda vars (loop (last b)))) (list exp)))
(cadar (let-assocs nested))))
(else
(define ret (cons (make-lambda vars (let-body b)) (list exp)))
(printf "ret: ~v~n" ret)
ret))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment