This post is the first (I hope) of a series about my adventure in Clojure land.

Being Clojure hosted on the JVM, it’s a natural choice for a Java developer wanting to study and learn functional languages.

A simple exercise

I started with a simple exercise: add all the natural numbers between 1 and 100 which are multiple of 5 or 7

; Add all the natural numbers below 100 that are multiples of 5 or 7.
(def r (range 1 100))

The lines starting with ; are comments.

The second line creates a range of numbers, starting from 1 to 100, and assigns the sequence to the symbol r.

I then defined a function which, given a number, returns true if the number is divisible by 5 or 7.

(defn divisibile [x]
  (if (== 0 (mod x 5)) true
    (if (== 0 (mod x 7)) true false)))

The following statement filters the range returning a list of the values which are divisible by 5 or 7.

(def validValues (filter #(divisibile %) r))

Then I sum the validValues, using the reduce function; int the following statement it applies the + operator to the elements of the sequence: if the sequence is (a b c), the expression  returns (a+b)+c

(def tot (reduce + validValues))
; print the result
(println tot)

I’m an absolute beginner in clojure and functional programming, so I would be happy to receive comments or suggestions. Thanks!

Enrico