English 中文(简体)
Applying a symbol as a procedure
原标题:
  • 时间:2009-11-21 12:32:49
  •  标签:
  • scheme

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

最佳回答

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

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!





相关问题
Parsing with DCGs in Scheme (without Prolog)?

Lots of Prolog-in-Scheme implementations are out there. E.g. Kanren, Schelog. Apparently in "Paradigms of AI Programming" Norvig implements Prolog-to-Lisp compiler in Lisp in order to use Definite ...

Applying a symbol as a procedure

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

string-split in DrScheme

How do I do equivalent of python s str.split in DrScheme? SRFI-13 doesn t seem to have it provided.

Scheme, getting the pointer from pointed struct

Assume I have a such struct: (define-struct node (value next)) ;and making 2 nodes, parent pointing to child as next. (define child (make-node 2 null)) (define parent (make-node 1 child)) Under ...

How to solve the following equation using accumulate (Scheme)

I m trying to do the following problem (there is a formula so I print-screened and uploaded it) Formula http://img248.imageshack.us/img248/6558/problemh.jpg (http://img248.imageshack.us/img248/6558/...

热门标签