Applying a symbol as a procedure

↘锁芯ラ 提交于 2019-12-20 03:08:10

问题


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 +?


回答1:


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. :)




回答2:


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)



回答3:


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!



来源:https://stackoverflow.com/questions/1775369/applying-a-symbol-as-a-procedure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!