Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected result of the function (recursion)

I need to implement the function which creates a list from arguments that are passed to the function.

Here's my code:

(defun lstbuilder (&rest args)
  (if (eq (car args) NIL)
      NIL
      (cons (car args)
            (lstbuilder (cdr args)))))

This function doesn't work correctly. Results:

(lstbuilder 'a 'b 'c 'd 'e) ;expected (a b c d e)
(a (b c d e)) ;result
like image 327
Alexander Hryk Avatar asked Feb 24 '26 03:02

Alexander Hryk


2 Answers

Style

  • Please use standard Lisp formatting. Use an editor will help you to indent Lisp code.

  • Don't put a parenthesis alone on a line. This just wastes space without benefit.

  • Longer names get a - between the words: list-builder.

  • Don't use carand cdr for list operations. Use first and rest.

  • The end of list test is endp.

Example:

(defun list-builder (&rest args)
  (if (endp args)
      nil
    (cons (first args)
          (apply #'list-builder (rest args)))))

Since the args variable is already a list, we can just copy it:

(defun list-builder (&rest args)
  (copy-list args))

Or we can just reuse the list function, which already creates a list of its args:

(setf (symbol-function 'list-builder)
      #'list)
like image 110
Rainer Joswig Avatar answered Feb 27 '26 02:02

Rainer Joswig


You need to use (apply #'lstbuilder (cdr args)) in order to "splat" the list's contents as the function call arguments.

like image 25
Chris Jester-Young Avatar answered Feb 27 '26 02:02

Chris Jester-Young



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!