Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Lisp Rocks

by BigGuy (Friar)
on May 25, 2001 at 07:57 UTC ( [id://83224]=note: print w/replies, xml ) Need Help??


in reply to Lisp Rocks

It's kind of funny that you post this now I am taking
comparitive programming languages right now and we are covering lisp
you have piqued my curiosity now i would like to see the
program now here is the very fisrt lisp program i have written actually it is not even that
just a little function
(defun multi-negative(alist) (cond ((null alist) 1); null list return nil ((and (numberp(car alist)) (< (car alist) 0) (* (multi-negative (cdr alist)) (car alist)))) (t (multi-negative(cdr alist))) );cond );defun

BigGuy "One World, one Web, one Program" - Microsoft promotional ad
"Ein Volk, ein Reich, ein Fuhrer" - Adolf Hitler

Replies are listed 'Best First'.
Re: Re: Lisp Rocks
by hding (Chaplain) on May 26, 2001 at 00:11 UTC

    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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://83224]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (7)
As of 2024-04-19 11:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found