3

For example, I want to define a function like this:

(defun operation (op)
  (op 3 7))

But the lisp compiler complains about code like this: (operation +)

Is there a way to pass arithmetic operator as function parameters?

rialmat
  • 133
  • 1
  • 6
  • possible duplicate of [how do I use a function as a variable in lisp?](http://stackoverflow.com/questions/6882502/how-do-i-use-a-function-as-a-variable-in-lisp) – Joshua Taylor Sep 27 '13 at 15:59
  • (That's actually not a great duplicate, but a better answer to it would be a good answer for this question.) – Joshua Taylor Sep 27 '13 at 16:04

1 Answers1

5

There are two categories of Lisp dialects: Lisp-1 and Lisp-2. Lisp-1 means that functions and variables share a single namespace. Scheme is a Lisp-1. Lisp-2 means that functions and variables have different namespaces. Common Lisp is a Lisp-2. If you want to pass a function named a as an argument to another function, you must refer to it as #'a. If you have a function stored in a variable, you can use the apply function to execute it. You code should work if it is rewritten like this:

(defun operation (op)
  (apply op '(3 7)))

(operation #'+)
Neil Forrester
  • 5,101
  • 29
  • 32
  • 4
    There's also the `funcall` function that's like `apply` but with the arguments expanded instead of collected into a list, so `(apply op '(3 7))` can also be written as `(funcall op 3 7)`. – Rörd Sep 27 '13 at 15:52
  • 2
    For more on when to use which, see [When do you use APPLY and when FUNCALL?](http://stackoverflow.com/q/3862394/1281433) – Joshua Taylor Sep 27 '13 at 16:04