Reputation: 1
I'm somewhat new to the Lisp language and I'm trying to write a function that trims off and returns part of a list. The code I've entered is as follows:
(defun trim-to (symbol list)
(cond
((null list) 0)
((equal symbol (car list)) (cons symbol (cdr list))
(t (trim-to (cdr list))))))
The code to run the function is:
(trim-to 'c '(a b c d e))
It is supposed to output (c d e)
but it only returns NIL
. Any idea what I did wrong with my code?
Upvotes: 0
Views: 464
Reputation: 38967
It is supposed to output (c d e) but it only returns NIL. Any idea what I did wrong with my code?
Here is your code, reformated:
(defun trim-to (symbol list)
(cond
((null list) 0)
((equal symbol (car list))
(cons symbol (cdr list))
(t (trim-to (cdr list))))))
When I compile it with SBCL, I have the following warning:
warning: The function T is undefined, and its name is reserved by ANSI CL so that even if it were defined later, the code doing so would not be portable.
Indeed, your code has the following form (t ...)
in a normal evaluation context; you intended it to be a clause in the cond
form, but there is a missing closing parenthesis before, which makes the (t ...)
form an expression to be evaluated after (cons symbol (cdr list))
(and by doing so, it makes that previous form useless since its result is discarded). An editor that hightlights matching parentheses could help you here (most of modern editors do it out of the box).
Since your test does not match the second clause of the cond
, the code didn't reach the part where you want to call a function named T
, and you didn't have an error at runtime. But the default value of a cond
form is NIL, which is why you see that result.
Without giving the full answer, here is the expected trace of execution for your example:
0: (TRIM-TO C (A B C D E))
1: (TRIM-TO C (B C D E))
2: (TRIM-TO C (C D E))
2: TRIM-TO returned (C D E)
1: TRIM-TO returned (C D E)
0: TRIM-TO returned (C D E)
Upvotes: 4