Just some (hopefully) constructive criticism. If I understand correctly, this is supposed to take a list of numbers and multiply only the negative ones together (or return 1 if there are none)? (Which to be fair, it does.) The intent is a little obscured - the second clause in the cond could be more clearly written - as is, you have the result you want as the third condition of the "and" rather than the result that is returned when the "and" clause tests to true - since "and" returns the value of the last argument if all of them are true, and since a cond clause returns the value of the test if it is true but no result clause is specified, this works, but is unclear. Also, the first comment is misleading. You might want to avoid using the name "alist" here - an alist is a specific type of data structure that Lisp programmers will probably expect to see here if you use that name (that threw me off a little at first!). You can just say "list". Finally, Lisp style generally tells us to avoid having parentheses alone on lines. A cleaned up version might be (oh, I slipped minusp in there too :-):
(defun multi-negative (list)
"Return the product of the negative numbers in list."
(cond ((null list) 1)
((and (numberp (car list)) (minusp (car list)))
(* (multi-negative (cdr list))
(car list)))
(t (multi-negative (cdr list)))))
There are lots of other fun ways to write this in Lisp, too. Have fun discovering them!
Update: Added a little clarification w.r.t. the "and" stuff. Also,
it'd be better to use realp than numberp, as minusp will choke
on a complex number.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|