Search code examples
functionlambdaschemeletchicken-scheme

Scheme: Convert from Let to Lambda


so I'm trying to experiment with some code and change between the two scheme expression methods of let and lambda.

The code I have is as follows:

(let splice ((l '()) (m (car s)) (r (cdr s)))
        (append
          (map (lambda (x) (cons m x)) (perm (append l r)))
          (if (null? r) '()
        (splice (cons m l) (car r) (cdr r)))))

I'm trying to change the outermost let definitions to lambda format, but it's a bit confusing due to the nested nature of the code. What I have attempted to do so far is:

(lambda (splice (l m r))
        (append
            (map (lambda (x) (cons m x)) (perm (append l r)))
            (if (null? r) '()
    (cut (cons m l) (car r) (cdr r)))))
(('()) (car upList) (cdr upList))

This is clearly wrong, but I don't know how to proceed further...


Solution

  • I wrote a post about how let is transformed into lambda behind the scenes, which you may find helpful.

    According to the expansion described in my post, your code would expand into:

    ((rec (splice l m r)
       (append (map (lambda (x) (cons m x)) (perm (append l r)))
               (if (null? r)
                   '()
                   (splice (cons m l) (car r) (cdr r)))))
     '() (car s) (cdr s))
    

    which then expands to:

    ((letrec ((splice (lambda (l m r)
                        (append (map (lambda (x) (cons m x)) (perm (append l r)))
                                (if (null? r)
                                    '()
                                    (splice (cons m l) (car r) (cdr r)))))))
       splice)
     '() (car s) (cdr s))