[Project Euler Problem 4 Solution] Thanks God, Clojure exists!!

I’ve tried several functional languages (OCaml, Haskell, Racket/Scheme) but Clojure is pure awesomeness.
This is a semi-trivial, not optimized solution to the problem 4 of Project Euler.
Note: you need the pattern-match jar, a wonderful way to bring pattern matching into your Clojure functions.
You can download it from Clojars or adding a dependency in Leningen:

(use 'pattern-match)

(defn palindrome? [num-as-string]
  (match num-as-string
	 [] true
	 [x] true
	 [x x] true
	 [x & xs] (if (= x (last xs)) (palindrome? (butlast xs)) false)
	 _ false))

(sort (map (fn [x] (Integer. x))
	   (filter palindrome?
		   (for [n1 (range 100 999)
			 n2 (range 100 999) :let [k (* n1 n2)]] (str k)))))

In my opinion this version is very readable even if you are a beginner:

  • The nested for iter over two range, binding k to (* n1 n2), building a list of strings
  • The resulting list is passed to the filter function with the predicate palindrome? that checks if a number is palindrome
  • The outer map convert such filtered list in a integer list
  • The final sort sort the results because the problem wants the largest palindrome number




Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo di WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione /  Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione /  Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione /  Modifica )

Connessione a %s...