0

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.

3
  • 1
    Would it be ok to call it as (bind-function-name '+ (list param 'a "First"))?
    – sepp2k
    Oct 24, 2010 at 19:11
  • That does indeed work, is there any way I can use it with a second argument quoted to make it less verbose?
    – gct
    Oct 24, 2010 at 19:20
  • 1
    Well, you can always use quasiquotation: `(,param a "First") Oct 24, 2010 at 21:15

1 Answer 1

0

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.