In trying to learn Clojure and wrap my head around good functional programming, and hoping to learn more idiomatic Clojure, I have started working through the Project Euler problems. In doing this, I have also setup a repository on github.com to keep track of my progress, which can be found at https://github.com/stevenproctor/project-euler-clojure. My approach to Problem 3 can be found here.
Problem 4 of Project Euler is described as:
Find the largest palindrome made from the product of two 3-digit numbers.
The solution I came up with is:
(ns project-euler.core (:require [clojure.string :as string])) (defn is-palindrome? [s] (= (str s) (string/join (reverse (str s))))) (defn problem4 [] (apply max (filter is-palindrome? (for [x (range 100 1000) y (range 100 1000)] (* x y)))))
As I want to use the join function in the clojure.string namespace, I added the :require keyword and aliased clojure.string as string using the :as keyword from the namespace macro.
The function is-palindrome? converts the value into a string, reverses the stream of characters in the string and then joins them back together and then compares it with the value as a string.
As defined problem4 does the meat of the work, by using a for loop over the set of of values from 100 to 999 for the binding of x and y, and multiplies x and y for each combination. This set is then filtered against the is-palindrome function, and the filtered sequence is then passed to the max function via apply.
Again, I would love comments and suggestions on my solution to this problem, and if there are tweaks to make it more Clojure-ish.
**Update**
My solution to Problem 5 has been posted here.
–Proctor