开发者

Rebinding parameters to a function call in scheme>

开发者 https://www.devze.com 2023-01-21 00:13 出处:网络
I\'m a bit of a scheme newbie and I\'m trying to do write a function that 开发者_如何学编程takes a function name, and and an expression and binds the function name as the first argument of the express

I'm a bit of a scheme newbie and I'm trying to do write a function that 开发者_如何学编程takes a function name, and and an expression and binds the function name as the first argument of the expression.

IE:

Something like:

(bind-function-name '+ '(param 'a "First"))

Would produce a lambda that evaluates

(param '+ 'a "First")

Best I've come up with so far:

(define (bind-function-name name cmd) 
  (let ((func (car cmd)) (args (cdr cmd)))
    (lambda ()
      (apply func (cons name args)))))

Which doesn't seem to work, as it complains about the function name being a symbol.

I'm sure this is pretty simple, but I'm just missing something, thought someone could help me out.


First: you are mixing code and data. It looks alike in Scheme but it is not the same. Second: an expression does not have a first argument. Only a function call has a first argument.

So you do not talk about an expression but a function with an argument list. And if you have a function and a list of arguments, it is quite easy to write a bind function, which calls the original function with a modified argument list. It is done this way:

This is an old function, which takes some arguments and does anything with them:

(define (old-func . args)
  (display "old-func: ")
  (write args)
  (newline))

(old-func 1 2 3) -> old-func: (1 2 3)

This is the bind function wich takes the old function and a new first-argument and returns a new function which calls the old function with the modified argument list.

(define (bind-func first-arg old-func)
  (lambda args
    (apply old-func (cons first-arg args))))

And this is the way it works:

(define new-func (bind-func "new" old-func))
(new-func 1 2 3) -> old-func: ("new" 1 2 3)
0

精彩评论

暂无评论...
验证码 换一张
取 消