0
点赞
收藏
分享

微信扫一扫

scheme 把一个symbol变成一个procedure

飞空之羽 2022-03-30 阅读 165
开发语言

​​​​​​​​​​​​​​​​​​​​​Applying a symbol as a procedure

Ask Question

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

scheme

Share

Edit

Follow

edited Nov 21, 2009 at 12:57

asked Nov 21, 2009 at 12:32

Yuval Adam

155k8989 gold badges297297 silver badges388388 bronze badges

Add a comment

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)

Share

Edit

Follow

answered Dec 2, 2009 at 16:34

Davorak

7,17211 gold badge3535 silver badges4747 bronze badges

Add a comment

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!

Share

Edit

Follow

edited Nov 26, 2009 at 21:20

answered Nov 26, 2009 at 12:21

Ben Fitzgerald

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. 

    – Yuval Adam

     Nov 26, 2009 at 15:17
  • ah yes, see that now. Thanks Yuval. 

    – Ben Fitzgerald

     Nov 26, 2009 at 21:18

Add a comment

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

Share

Edit

Follow

answered Nov 21, 2009 at 12:36

Lucas Jones

19.2k88 gold badges7373 silver badges8888 bronze badges

  • So simple, dunno how I missed that out. Thx! :) 

    – Yuval Adam

     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
举报

相关推荐

0 条评论