scheme 把一个symbol变成一个procedure

本文探讨了在Scheme语言中如何将符号(如 '+)应用为实际的过程或函数。通过使用eval函数或定义特定的宏,可以实现这一目标,同时确保代码的安全性和灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

​​​​​​​​​​​​​​​​​​​​​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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值