3
votes

This is my first time working with racket, and I am getting an error message (*: unbound identifier;) when trying to evaluate a list in Dr. Racket.

#lang racket
(define (randop)
  (define x(random 3))
  (cond
    ((= x 0) '+)
    ((= x 1) '-)
    ((= x 2) '*)
   )
)

(define (randexp ht)
   (define x(random 10))
   (define y(random 10))
   (define z(randop))
  (eval (list z y x))
)

(randexp 1)

When executing racket in the console, (eval lst) works fine, though when I execute this code, it comes up with an unbound identifier. Any help is appreciated.

2

2 Answers

2
votes

There's a problem with the way you're calling eval, in Racket you have to do this in a file:

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

(define (randop)
  (define x (random 3))
  (cond
    ((= x 0) '+)
    ((= x 1) '-)
    ((= x 2) '*)))

(define (randexp ht)
  (define x (random 10))
  (define y (random 10))
  (define z (randop))
  (eval (list z y x) ns))

(randexp 1)

Also, you're not actually using the ht parameter, consider deleting it.

3
votes

You don't need eval here. Instead of returning the symbols return the procedures instead:

#lang racket

(define (randop)
  (define x (random 3))
  (cond ((= x 0) +) ; + not quoted means if will return what + evaluates to
        ((= x 1) -) ; which is the procedures they represent
        ((= x 2) *)))

(define (randexp)
   (define x (random 10))
   (define y (random 10))
   (define z (randop))
   (z y x))) ; call z (the procedure returned by randop) with arguments x and y.

(randexp)