Схема улучшения лямбда-редукции - PullRequest
0 голосов
/ 21 марта 2012

Я переписываю этот вопрос, так как он был плохо сформирован.

(define (reduce f)                                                        
((lambda (value) (if (equal? value f) f (reduce value)))                 
(let r ((f f) (g ()))                                                  
(cond ((not (pair? f))                                                
(if (null? g) f (if (eq? f (car g)) (cadr g) (r f (caddr g))))) 
((and (pair? (car f)) (= 2 (length f)) (eq? 'lambda (caar f)))  
(r (caddar f) (list (cadar f) (r (cadr f) g) g)))              
((and (not (null? g)) (= 3 (length f)) (eq? 'lambda (car f)))    
(cons 'lambda (r (cdr f) (list (cadr f) (gensym (cadr f)) g))))  
(else (map (lambda (x) (r x g)) f))))))                          

; (reduce '((lambda x x) 3)) ==> 3
; (reduce '((lambda x (x x)) (lambda x (lambda y (x y)))))
;   ==> (lambda #[promise 2] (lambda #[promise 3] (#[promise 2] #[promise 3])))

; Comments: f is the form to be evaluated, and g is the local assignment
; function; g has the structure (variable value g2), where g2 contains
; the rest of the assignments.  The named let function r executes one
; pass through a form.  The arguments to r are a form f, and an
; assignment function g.  Line 2: continue to process the form until
; there are no more conversions left.  Line 4 (substitution): If f is
; atomic [or if it is a promise], check to see if matches any variable
; in g and if so replace it with the new value.  Line 6 (beta
; reduction): if f has the form ((lambda variable body) argument), it is
; a lambda form being applied to an argument, so perform lambda
; conversion.  Remember to evaluate the argument too!  Line 8 (alpha
; reduction): if f has the form (lambda variable body), replace the
; variable and its free occurences in the body with a unique object to
; prevent accidental variable collision.  [In this implementation a
; unique object is constructed by building a promise.  Note that the
; identity of the original variable can be recovered if you ever care by
; forcing the promise.]  Line 10: recurse down the subparts of f.

У меня есть приведенный выше код, который выполняет лямбда-сокращение лямбда-выражения (что я и хочу).Моя проблема здесь в том, может ли кто-нибудь помочь мне переписать эту реализацию (поскольку я не очень разбираюсь в Scheme), чтобы я извлек из тела часть, которая выполняет альфа-преобразование, и поместил ее в отдельную функцию, а часть, которая выполняетбета-сокращение также.Функция Reduce является рекурсивной, поэтому две новые созданные функции должны быть одношаговыми, то есть они будут преобразовывать только одну ограниченную переменную и сокращать только одно выражение.

1 Ответ

1 голос
/ 21 марта 2012

Ваш набор требований ясно показывает мне, что это домашняя работа;если я ошибаюсь, дайте мне знать, откуда берутся ваши ограничения:).

Мне кажется, вам нужно лучше понять вопрос, прежде чем приступить к разработке решения.Первое, что вы упоминаете, это альфа-преобразование, и я думаю, что это хорошее место для начала.Можете ли вы написать несколько примеров того, как вы могли бы вызвать функцию альфа-преобразования и что она может вернуть?

...