Better Lisp code

2006-07-20 23:16:51 PST

Tags: , ,

So. Yes my Primes suite is a bad benchmark at times. Crude certainly. But also unfair for languages that I don't know well. Remember when I was surprised at how "slow" the lisp results were? Well my bad. I got Paul Graham's "ANSI Common Lisp" for my birthday on the 12th. Been doing some reading. I'm starting to get the idea behind lisp, and actually haskell too. Functional programing, programing with out side effects. Lots of recursion. Which normally I only use in certain circumstances but not in place of loops because it's innefficient. So my Lisp code used a loop. Well, it turns out that little did I know functional languages like these have something called "tail loops" (the recursive call is the last part of a function) and they can be optimized to goto loops or something. So I wrote a new primes in lisp.

primes2.cl

(defun check (max i sq)
  (if (> i sq)
    (format t "~d~%" max)
    (if (not (= (mod max i) 0))
      (check max (+ i 2) sq))))

(defun _primes (max i)
  (if (< i max)
    (progn
      (check i 3 (sqrt i))
      (_primes max (+ i 2)))))

(defun primes (max)
  (_primes max 3))
results.1000000.txt

(22/36) Common Lisp results:
Execute [sbcl]:         5.21 seconds

That's better looking. And I'm still just a total beginner. Cool though.

Food for after thought: I took a look at a haskel intro linked to on reddit and for the first time ever stuff about haskell actually made sense to me. Being a functional language like lisp, and having a list data type, like lisp, it's actually got surprisingly strong similarities. Huh.
Also, sadly, currently Ruby doesn't have tail recursion optimization, I've heard it said VARV (the ruby VM) in the next version of Ruby will support it.

Leave a Reply

Valid XHTML 1.0!
Valid CSS!
Mindstab.net is proudly powered by WordPress
Entries (RSS) and Comments (RSS).
20 queries. 0.396 seconds.