Woo hoo!

Whatever is on your mind, whether Lisp related or not.

Woo hoo!

Postby mrdelurk » Wed Oct 14, 2015 9:30 pm

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.)
mrdelurk
 
Posts: 7
Joined: Thu Oct 08, 2015 1:43 pm

Re: Woo hoo!

Postby Goheeca » Sun Oct 18, 2015 9:34 am

Not necessarily:
Code: Select all
(defun firstzero (x y z)
  (cond ((= 0 x) 'first)
        ((= 0 y) 'second)
        ((= 0 z) 'third)
        (t 'none)))

a minimal form of the code above:
Code: Select all
(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):
Code: Select all
(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:
Code: Select all
(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.
User avatar
Goheeca
 
Posts: 271
Joined: Thu May 10, 2012 12:54 pm

Re: Woo hoo!

Postby mrdelurk » Sun Oct 25, 2015 11:17 am

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-)
mrdelurk
 
Posts: 7
Joined: Thu Oct 08, 2015 1:43 pm


Return to The Lounge

Who is online

Users browsing this forum: No registered users and 2 guests