0
votes

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.

1
Would it be ok to call it as (bind-function-name '+ (list param 'a "First"))?sepp2k
That does indeed work, is there any way I can use it with a second argument quoted to make it less verbose?gct
Well, you can always use quasiquotation: `(,param a "First")Chris Jester-Young

1 Answers

0
votes

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)