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?

2
  • possible duplicate of how do I use a function as a variable in lisp? Commented Sep 27, 2013 at 15:59
  • (That's actually not a great duplicate, but a better answer to it would be a good answer for this question.) Commented Sep 27, 2013 at 16:04

1 Answer 1

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 #'+)
Sign up to request clarification or add additional context in comments.

2 Comments

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).
For more on when to use which, see When do you use APPLY and when FUNCALL?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.