This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

Woo hoo!

3 posts · 4596 views

Programming n00b, I was solving the book question, "Write a function FIRSTZERO that takes 3 numbers as input and returns a word (one of "first," "second," or "none") indicating where the first zero appears."

So I wrote (defun firstzero (x y z) (if (= x 0) 'first (if (= y 0) 'second (if (= z 0) 'third 'none)))) All done in 92 characters and it works.

Then I went to solutions to check if I got it right. Wow, the author did it with cond instead? (defun firstzero (x) (cond ((zerop (first x)) 'first) ((zerop (second x)) 'second) ((zerop (third x)) 'third) (t 'none))) 121 whopping characters and the numbers must be in list form too!

Did I just outcode the book? I'll be hovering above ground for the rest of the day with little pink trumpeting aureolae circles from happiness. If this was by design to make me feel great, thanks. One is proudest about things one is a n00b at.

(Tomorrow once I'm back on solid ground, feel free to point out how this could be far shorter with a macro. :mrgreen: Macros are still 300 pages away.)

Re: Woo hoo!

Not necessarily:
(defun firstzero (x y z)
  (cond ((= 0 x) 'first)
        ((= 0 y) 'second)
        ((= 0 z) 'third)
        (t 'none)))
a minimal form of the code above:
(defun firstzero(x y z)(cond((= 0 x)'first)((= 0 y)'second)((= 0 z)'third)(t'none)))
It has 84 characters.

But yeah, your code after minimalization is shorter (for three arguments though):
(defun firstzero(x y z)(if(= x 0)'first(if(= y 0)'second(if(= z 0)'third'none))))
81 characters.

My solution for unlimited count of arguments:
(defun z(&rest a)(if #0=(position 0 a)(intern(substitute #\- #\ (format nil"~:@(~:R~)"(1+ #0#))))'none))
106 characters long.

Well, let's do the code golf. :)
cl-2dsyntax is my attempt to create a Python-like reader. My mirror of CLHS (and the dark themed version). Temporary mirrors of aferomentioned: CLHS and a dark version.

Re: Woo hoo!

Thank you for the masterful reply, Goheeca
A week later, I'm still studying some of your solution's elements to grok how it works 8-)