Search code examples
lispcommon-lisplispworks

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>
}

Solution

  • 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).