Reputation: 21
is it possible to give procedure definition as an argument and then somehow run it in the program? For example if I call (program 'write-hello '((procedure write-hello ('Hello.))))
. How can I read the procedure from argument? I spent few hours on it and can't really find any solution to it as I'm new to Scheme.
Thanks
Upvotes: 1
Views: 987
Reputation: 49803
Functions are first class citizens in Scheme: they are values that can be passed just like the more traditional data types, and the parameter name can be used as if there were a function with that name defined in the traditional way.
If you have defined a function in the normal way (using define
), then you can just pass the name. But you can also make a function object using lambda
, which can be used like any other value (bound to names, passed as an argument) in addition to its function-like abilities (i.e. applied to arguments).
The following are equivalent:
(define (plus a b) (+ a b))
(define plus_a (lambda (a b) (+ a b)))
And if you have the following (notice how op
is being used):
(define (do_op op a b) (op a b))
Then these would also be equivalent to each other:
(do_op + 5 6)
(do_op plus 5 6)
(do_op plus_a 5 6)
(do_op (lambda (a b) (+ a b)) 5 6)
Upvotes: 1
Reputation: 48745
For Scheme you just pass the lambda definition like (lambda (n) (* n n))
eg.
(define (display-result procedure value)
(display (procedure value))
(display-result (lambda (n) (* n n)) 5) ; displays 25
If a procedure is bound to a name, like +
or defined with define
you just use that name in place of the lambda expression.
If you are after making an interpreter of some language then you need to implement this feature yourself by managing your own environment. It's not simple and if you're a newbie it will take more than hours to complete. I recomment watching the SICP videos.
Upvotes: 0