P.C.
P.C.

Reputation: 649

How can I define a LISP function, which takes in an array as an argument?

I want to create an array in a function and pass it as a parameter to another function, which is called from that function. How can I do that? Here's the pseudo code:

define FuncA (Array Q){
    <whatever>
}

define FuncB (n){
    make-array myArray = {0,0,....0}; <initialise an array of n elements with zeroes>
    FuncA(myArray); <call FuncA from FuncB with myArray as an argument>
}

Upvotes: 0

Views: 1490

Answers (1)

uselpa
uselpa

Reputation: 18927

Common Lisp is dynamically typed, so an array parameter is declared in the same way as any other parameter, without its type:

(defun funcA (Q)
  Q) ; just return the parameter

(defun funcB (n)
  (let ((arr (make-array n :initial-element 0)))
    (funcA arr)))

or, if you don't need create a binding, simply

(defun funcB (n)
  (funcA (make-array n :initial-element 0)))

Testing

? (funcB 10)
#(0 0 0 0 0 0 0 0 0 0)

If you want to check that the parameter is of the expected type, you can use typep, type-of, typecase or check-type, for example:

(defun funcA (Q)
  (check-type Q array)
  Q)

then

? (funcA 10)
> Error: The value 10 is not of the expected type ARRAY.
> While executing: FUNCA, in process Listener(4).

Upvotes: 8

Related Questions