views:

51

answers:

2

How we can achieve variables that we defined in the (local ...) syntax in Scheme? For example in this code below,

(define (erkan x)
   (local 
      ((define y 10))
      (* x y)))

how can I directly get the value of y ?

+2  A: 

You are accessing y when you're doing (* x y).

If you want to access y from outside of the local-block: you can't do that. Any definitions made inside a local-block are local to that block and cannot be accessed from outside.

sepp2k
+1  A: 

Either this is a strange question, or you didn't phrase it right... Your sample code uses y, so it does have access to it. Maybe you're trying to get just the value of y:

(define (erkan x) (local [(define y 10)] y))

Or maybe you want to create a kind of an "object thing" -- this is possible, but involves more advanced code. Here's a quick example just to show you how it's done, (but if you're going through HtDP, you're better off leaving this for later).

(define (erkan x)
  (local [(define y 10)
          (define (handler message)
            (cond
              [(eq? message 'get-x) x]
              [(eq? message 'get-y) y]
              [(eq? message 'compute) (* x y)]
              [else (error "bad message")]))]
    handler))
(define some-erkan (erkan 3))
(some-erkan 'get-x)
(some-erkan 'get-y)
(some-erkan 'compute)

(Note BTW that this is not proper Scheme, but the teaching student dialects used in HtDP.)

Eli Barzilay
yes, studying HtDP.when i call (erkan 3), result is (lambda (a1) ...) in DrScheme. It is interesting (:What is the name of this method? maybe i can look at it from the book.
erkangur
It's really best to just go with the book in order -- it will also cover some of the more advanced things, and in a way that will be more understandable than some random piece of code...
Eli Barzilay