tags:

views:

53

answers:

2

I'm very new to lisp and recently i discovered the thin that I don't understand.

This code works:

(define (f x) (define a x) (define (b) a) (b))

And this doesn't:

(define (f x) (define a x) (define b a) b)

Why?

+3  A: 

In kawa interpeter it works In Guile it dasn't, becouse this code

(define (f x) (define a x) (define b a) b)

is expand to

(define (f x) (letrec ((a x) (b a)) b))

And you can't access to a before I's assign. letrec won't work for non-function definitions, for example:

(letrec ((x 5)
         (y x))
     y)

You can use let* insted

(define (f x) (let* ((a x) (b a)) b))

In this code

(define (f x) (define a x) (define (b) a) (b))

In procudere b you access a varible when it's already defined.

jcubic
Two problems in this question: *Some* versions of `letrec`s won't work, not all (specifically, those that implement it as a `letrec*`). Also, those that implement a stricter `letrec` won't allow using a bound name in one of the (other) expressions -- there is no Scheme implementation that restricts them only to functions. (OTOH, ML does.)
Eli Barzilay
+1  A: 

You should look up discussions about letrec* -- some implementations use it as a more permissive version of the stricter letrec, which results in the difference you see.

Eli Barzilay