modeller
modeller

Reputation: 3850

How to change the order of function body execution?

I am studying the Emacs-Lisp by following the introduction.

I can understand the below defun print out a list in left-to-right order because the print command comes before recursion (as I understood):

  (defun print-elements-recursively (list)
   "Print each element of LIST on a line of its own.
 Uses recursion."
   (when list                            ; do-again-test
         (print (car list))              ; body
         (print-elements-recursively     ; recursive call
          (cdr list))))                  ; next-step-expression

E.g. for a list of '(gazelle giraffe lion tiger). The print order is gazelle, giraffe, lion, tiger.

However, I could not understand why the same order still holds when I switch the position of the two expression within the when body:

(defun print-elements-recursively (list)
   "Print each element of LIST on a line of its own.
 Uses recursion."
   (when list                            ; do-again-test
                       ; body
         (print-elements-recursively     ; recursive call
          (cdr list))
         (print (car list))))                  ; next-step-expression

Per my expectation, the recursion happens before the print function, therefore, the order should be reversed. May I know why?

Upvotes: 1

Views: 67

Answers (1)

itsjeyd
itsjeyd

Reputation: 5280

You probably did not evaluate the second defun after defining it, and that is why the items of the input list are still being printed in the original order. Adding a second function with the same name to the global namespace does not mean that the definition of the first function is automatically overwritten.

I suggest you

  • rename one of the defuns
  • evaluate them both
  • and then call each one of them separately.

The behavior should not persist when you do that.


Aside from printing the elements of the list in a different order, note also that the original function returns nil and the second function returns a printed representation of the last (non-nil) item of the input list. This is because (when list) returns nil and is the last expression that gets evaluated when the base case is reached in the first function. In the second function all invocations of print are evaluated after the base case is reached.

Upvotes: 2

Related Questions