Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are function parameters stored in lisp?

I assumed that values passed into a lisp function are assigned to a quote matching the name of the parameter. However, I was surprised that this:

(defun test (x) (print (eval 'x)))
(test 5)

doesn't work (the variable x is unbound). So if parameters aren't stored as symbols in the function, what exactly IS x in this example? Is there a way to access parameters from a symbol matching the parameter name?

More context: What I would like to do is something like this:

defun slice (r1 c1 r2 c2 board)
  (dolist (param '(r1 c1 r2 c2))  ;adjust for negative indices
    (if (< (eval param) 0)
      (set param (+ (length board) (eval param)))))
        ;Body of function

Basically, I want to iterate through the first four parameters and make an adjustment to any of their values if they are < 0. Of course, I could do a let and have an individual line for each parameter, but considering I'm doing the same thing for each of the four parameters this seemed cleaner. However, I get the error that the variable R1 is unbound.

like image 250
rcorre Avatar asked Oct 16 '13 15:10

rcorre


People also ask

Where are function parameters stored in memory?

Parameter values to functions are stored on the stack as well, pushed immediately before the return address. Everything what lives on the stack (local variables, parameters etc.) can live in registers as well.

How do you define a function in a Common Lisp?

Use defun to define your own functions in LISP. Defun requires you to provide three things. The first is the name of the function, the second is a list of parameters for the function, and the third is the body of the function -- i.e. LISP instructions that tell the interpreter what to do when the function is called.

Are there variables in Lisp?

LISP supports two types of variables: Local variables. Global variables.

What does Funcall do in Lisp?

Description: funcall applies function to args. If function is a symbol, it is coerced to a function as if by finding its functional value in the global environment.


1 Answers

That's basically how lexical binding works: the variable name gets replaced within the lexical scope with a direct reference to where the variable's value is stored. Binding the variable name's symbol-value is only done for dynamic variable which you can declare with special.

One way to avoid repeating yourself would be a macro:

(defmacro with-adjusting ((&rest vars) adjust-value &body body)
  `(let ,(loop for var in vars
               collect `(,var (if (minusp ,var)
                                (+ ,var ,adjust-value)
                                ,var)))
     ,@body))

(defun slice (r1 c1 r2 c2 board)
  (with-adjusting (r1 c1 r2 c2) (length board)
    ;; function body
like image 150
Rörd Avatar answered Oct 06 '22 18:10

Rörd