… 10 one-liners

A lot of people have responded to 10 Scala One Liners with implementations in a lot of different languages, including clojure. My suggestion can be found in this gist but one of the one-liners are especially interesting, Sieve of Eratosthenes.

There are a lot of different versions of this algorithm. This one is translated from Miranda, an old classic from Bird & Wadler, Introduction to Functional Programming, p.175, and goes something like this:

(defn sieve [xs]
  (filter #(not (zero? (mod % (first xs)))) (rest xs)))

(defn rsieve [xs]
  (map first (iterate sieve xs)))

(defn primes-below [max]
  (take-while #(not (nil? %)) 
	      (rsieve (range 2 max))))

Unfortunately, it blows the stack for large values, but I still like this simple compact definition.

This entry was posted in clojure and tagged . Bookmark the permalink.

2 Responses to … 10 one-liners

  1. Mark says:

    It’s not a huge problem if this program blows the stack for large values, but it *is* a huge problem if it is not immediately obvious *why* it blows the stack. At first glance, all of these functions operate lazily on lazy sequences, so there’s no reason to think it would blow the stack. It seems to me that your code snippet is an argument that Clojure lacks transparency and the ability to reason about the safety of one’s program.

    • klang says:

      An infinite list of infinite lists are not handled in the right way in this case, that’s for sure. There is some “holding onto the head” going on, I suppose.

Comments are closed.