Question

I have a little noob question. I have to do a homework on genetic programming in scheme and the first step is to finish some given functions.

I got to a point where i have to execute a randomly generated function with all the possible parameters in a range (using map). The "function" is list like '(* (+ 1 x) (- x (* 2 3))).

How can i execute it with a given parameter? (for example x = 2). By the way, the generated function has a maximum of 1 parameter (it's x or none).

Thanks!

Was it helpful?

Solution

Here's my solution:

(define (execute expr)
  (lambda (x)
    (let recur ((expr expr))
      (case expr
        ((x) x)
        ((+) +)
        ((-) -)
        ((*) *)
        ((/) /)
        (else
         (if (list? expr)
             (apply (recur (car expr)) (map recur (cdr expr)))
             expr))))))

Example usage:

> (define foo (execute '(* (+ 1 x) (- x (* 2 3)))))
> (foo 42)
=> 1548
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top