lispquestions
lispquestions

Reputation: 441

lisp: properly form if statement

As a task for myself to learn common lisp, I'm trying to recreate lodash.

En route to recreating _.chunk, I've written the following to test for an optional argument

(defun _.chunk (array &optional size)
    (if (size)
        (write ("there") )
        (write ("not") )
    ) 
)  

Setting (setf x #('a 'b 'c 'd)) and then running (_.chunk x), I get an error:

; caught ERROR:
;   illegal function call

;     (SB-INT:NAMED-LAMBDA _.CHUNK
;         (ARRAY &OPTIONAL SIZE)
;       (BLOCK _.CHUNK
;         (IF (SIZE)
;             (WRITE ("there"))
;             (WRITE ("not"))))) 

What's the correct way to test for optional function parameters?

Upvotes: 1

Views: 102

Answers (1)

Simeon Ikudabo
Simeon Ikudabo

Reputation: 2190

size-p, the name of the optional variable which may be specified after the default value of a keyword or optional argument, will be true if the parameter was passed as an argument to a function call.

so you could do something such as:

(defun _.chuck (array &optional (size 0 size-p))
  (if size-p
      (rest of your form...)))

Upvotes: 6

Related Questions