tags:

views:

80

answers:

3

Suppose I have a simple symbol:

> '+
+

Is there any way I can apply that symbol as a procedure:

> ((do-something-with '+) 1 2)
3

So that '+ is evaluated to the procedure +?

+8  A: 

I'm not 100% sure, but would:

((eval '+) 1 2)

work? I'm not sure if you need to specify the environment, or even if that works - I'm a Scheme noob. :)

Lucas Jones
So simple, dunno how I missed that out. Thx! :)
Yuval A
No problem! (15 char.)
Lucas Jones
A: 

Newbie too so hope I've understood your question correctly...

Functions are first class objects in scheme so you don't need eval:

1 ]=> (define plus +)

;Value: plus

1 ]=> (plus 2 3)

;Value: 5

HTH

Update: Ignore this and see the comments!

Ben
@Ben - you missed the part where the `+` is quoted, hence, it is not directly a procedure until it is evaluated.
Yuval A
ah yes, see that now. Thanks Yuval.
Ben
+1  A: 

Lucas's answer is great. For untrusted input you can make a white list of allowed symbols/operators.

(define do-something (lambda (op)
                       (cond
                         ((equal? op `+) +)
                         ((equal? op `-) -)
                         ((equal? op `*) *)
                         ((equal? op `/) /)
                         ((equal? op `^) ^))))

((do-something `+) 1 2)
Davorak