Applying a symbol as a procedure
Asked 12 years, 4 months ago
Modified 12 years, 3 months ago
Viewed 1k times
Report this ad
2
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 +
?
Follow
asked Nov 21, 2009 at 12:32
155k8989 gold badges297297 silver badges388388 bronze badges
3 Answers
Sorted by:Reset to default
Highest score (default) Date modified (newest first) Date created (oldest first)
3
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)
Follow
answered Dec 2, 2009 at 16:34
7,17211 gold badge3535 silver badges4747 bronze badges
Report this ad
0
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!
Follow
answered Nov 26, 2009 at 12:21
76311 gold badge66 silver badges1919 bronze badges
- @Ben - you missed the part where the
+
is quoted, hence, it is not directly a procedure until it is evaluated. Nov 26, 2009 at 15:17 - ah yes, see that now. Thanks Yuval. Nov 26, 2009 at 21:18
8
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. :)
Follow
answered Nov 21, 2009 at 12:36
19.2k88 gold badges7373 silver badges8888 bronze badges
- So simple, dunno how I missed that out. Thx! :) Nov 21, 2009 at 12:39
-
1
If you want it to work with any environment you should probably use(eval '+ (null-environment 5))
– Joe D
Dec 5, 2010 at 9:39