thesook
thesook

Reputation: 23

How to return string containing evaluated arguments of procedure?

Using Racket, I want to design a procedure that takes as its inputs a binary operation and two arguments a & b of any type, evaluates the binary operation on the arguments, and returns a string describing the result of the evaluation. For example, if my procedure were called foo, then

(foo + 1 2)
(foo cons 'bar empty)

would return

The + of 1 and 2 is: 3
The cons of 'bar and empty is: (bar)

My code would look something like

(define (foo op a b)
    (let ((result (op a b)))
      (display
       (string-append
        "The "
        (arg->string op)
        " of "
        (arg->string a)
        " and " 
        (arg->string b)
        " is: "
        (arg->string result)
        ))))

Is it possible to construct some operation arg->string that would do what I want (namely, evaluate its argument before converting to a string?). Simply constructing a string or quoting the argument within the body of the procedure returns the literal result, i.e. "op" or 'op instead of "+" or '+.

Any help is appreciated.

Upvotes: 2

Views: 2620

Answers (1)

Óscar López
Óscar López

Reputation: 235984

This solution is the simplest that comes to mind:

(define (foo op a b)
  (printf "The ~s of ~s and ~s is: ~s\n"
          (object-name op) a b (op a b)))

See if this works for you:

(foo + 1 2)
> The + of 1 and 2 is: 3

(foo cons 'bar empty)
> The cons of bar and () is: (bar)

Upvotes: 3

Related Questions