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 ?
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 ?
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.
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.)