asuran_zala
asuran_zala

Reputation: 51

how assign values to variables in racket?

if I have this list

'((x 3) (y 4) (z 2))

how do I assign 3 to x and y to 4 and z to 2 to use it to do math like?

3 + x

or

y + z

Thanks

Upvotes: 5

Views: 13337

Answers (2)

Óscar López
Óscar López

Reputation: 235984

You can use let to declare local variables in Scheme. For example, to create bindings with the given values in the list:

(let ((x 3) (y 4) (z 2))
  (+ y z)) ; body

=> 6

Now you can evaluate any expression involving the declared variables in the <body> part. You can even create a let from a list of bindings, for instance using macros:

(define-namespace-anchor a)
(define ns (namespace-anchor->namespace a))

(define-syntax my-let
  (syntax-rules ()
    [(_ lst exp)
     (eval `(let ,lst ,exp) ns)]))

(my-let '((x 3) (y 4) (z 2)) ; bindings as an association list
        '(+ y z))            ; expression to be evaluated

=> 6

The above creates a macro called my-let which receives a list of bindings and an expression to be evaluated with those bindings, and returns the result of the evaluation.

Upvotes: 6

uselpa
uselpa

Reputation: 18917

A simple, straightforward and portable way would be to define an accessor (in this example, getval) using assq:

(define vars '((x 3) (y 4) (z 2)))
(define (getval sym) (cadr (assq sym vars)))

or any variation thereof. Then use as follows:

(+ 3 (getval 'x))
=> 6

(+ (getval 'y) (getval 'z))
=> 6

Upvotes: 2

Related Questions