Merl's Blog

For Loop?

One of my favorite tools in Python and C was the for loop. It was so simple, and straight forward. I was concerned about going into Clojure.

Luckily Clojure has something similar but more powerful.

Before I get into that I want to describe the problem I was solving. It was Euler problem 4 and it was: Find the largest palindrome made from the product of two -digit numbers.

Went back to my old ways and forced a loop to check the answer. My thought process was to create 2 loops. Start at 100, the smallest 3 digit number, for both numbers. Then increase the first number up to 999, the largest 3 digit number, then increase the second number to 101 and cycle the first number again.

While looping through these numbers, I find the product of those numbers. I wrote a function called palindrome to check if that product was a palindrome. After cycling through all of the possibilities I found the largest palindrome and found my answer.

Here is the code:

(defn euler-4 [start end]
 (loop [i start
        j start
        max-palindrome 0]
   (if (< i end)
     (if (< j end)
       (let [product (* i j)]
         (if (and (palindrome? product) (> product max-palindrome))
           (recur i (inc j) product)
           (recur i (inc j) max-palindrome)))
       (recur (inc i) i max-palindrome))
     max-palindrome)))


This could be cleaner, but for being new to Clojure it’s not bad. That’s me speaking by the way.

Now we get back to the for discussion I was mentioning earlier. The the for loop in Python is used for iterating over a sequence. The for function in clojure is a list comprehension, where it provides a concise way to create lists based on existing lists, arrays, or other iterable objects

Instead of writing out all of the loops in Clojure we can use the list comprehension.

(defn euler-4 [start end]
 (->> (for [i (range start end) j (range i end)] [i j])
      (map #(apply * %))
      (filter palindrome?)
      (apply max)))

This is much cleaner. We have that list comprehension at the top, we find the product of it, then filter if it’s a palindrome, and finally bring out the max.

This follows a logical framework that isn’t hiding behind a lot of simple unnecessary code.

Best,

Merl