Code: Select all
1. (defun my-length (list) 2. (if list 3. (1+ (my-length (cdr list))) 4. 0)) > (my-length '(list with four objects)) 4
1. We're defining the function 'my-length' which takes one argument 'list'
2. If the argument exists and is not empty, eg () or nil
3. do the following:
Pass '(with four objects) to the function my-length. It's recursive so then it'll pass '(four objects) to my-length until the list is empty.
What I don't understand here is "(1+" I thought that (1+ n) = (+ n 1). If that's correct, the recursive function adds:
'(list with four objects) + 1
'(with four objects) + 1
'(four objects) + 1
'(objects) + 1
Which doesn't make sense to me. How can you add strings and numbers? I can see that that's probably not the case. That each iteration 1 gets added to make the total of 4 (number of elements) but according to the code it seems to me that it gets added to the list of strings?!
Could you please explain how it really works? Thank you for your time and patience.