Code: Select all
(defun our-member (obj lst)
(if (null lst)
nil
(if (eql (car lst) obj)
lst
(our-member obj (cdr lst)))))
Code: Select all
(defun our-member (obj lst)
(if (null lst)
nil
(if (eql (car lst) obj)
lst
(our-member obj (cdr lst)))))
Nil is the default value returned if the list is empty, that is why it is there. If you remove it, the last if is evaluated only when the list is empty, which won't work.yougene wrote:Taking out the nil breaks the code. Why?Code: Select all
(defun our-member (obj lst) (if (null lst) nil (if (eql (car lst) obj) lst (our-member obj (cdr lst)))))
It is not a line, it is a form, and not a command but a possibly side effecting expression. This is not just semantics, understanding the meaning of these words is crucial to understanding Lisp. And no, if the IF form has only two arguments then the second one, which will in that case be last, would be a "then" expression, and the else branch would be an implicit NIL. When you removed the NIL in your original post you effectively exchanged the branches.yougene wrote:Does this mean that the last line is always assumed to be the command for "else"?
Code: Select all
(if (null lst)
(format T "then")
(format T "else")
)
(if (null lst)
(format T "then")
(format T "else")
(format T "umm...?") ; <= not working!!!
)
Code: Select all
(when (null lst)
(format T "statement1")
(format T "statement2")
(format T "statement3")
)
Code: Select all
(if (null lst)
(progn ; encapsulates the whole then block
(format T "statement1")
(format T "statement2")
(format T "statement3")
)
(format T "else")
)
That is true for Common Lisp, but for example in Emacs Lisp all forms after the second form an implicit PROGN for the else clause. Some people even use an IF* macro like this in CL, although I don't really think this is all that useful.hewih wrote:in if you can only have 1 form for then and 1 form for else. the other way around, how would Lisp know which form belongs to then and which to else
Even better, use COND. This is of course subjective, but I don't think I am alone in thinking that is clearer, even for just two branches.hewih wrote:if you need more statements in then or else, use progn
Code: Select all
(defun our-member (obj lst)
(if (null lst)
nil
(if (eql (car lst) obj)
lst
(our-member obj (cdr lst)))))
Code: Select all
(defun our-member (obj lst)
(cond
((null lst)
nil)
((eql (car lst) obj)
lst)
(t
(our-member obj (cdr lst)))))
Code: Select all
(defun our-member (obj lst)
(cond
((null lst) nil)
((eql (car lst) obj) lst)
(t (our-member obj (cdr lst)))))
Code: Select all
(defun our-member (obj lst)
(unless (null lst)
(if (eql (car lst) obj)
lst
(our-member obj (cdr lst)))))