Starting with Clojure: Factorial function

My background is mainly C# with some JavaScript. I have heard a lot about functional programming languages like Clojure, F# and Scala.

I decided to start learning Clojure.

My first reaction after seeing a Clojure code was the syntax and layout which was unreadable to me.

Clojure is a member of the Lisp family of languages. The use of parentheses is prominent.

Below is some code that calculates factorial of a number in Clojure

(defn fac
"Returns factorial of n"
[n]
(if (= n 1)
1
(* n (fac (- n 1)))))

Parentheses are used to structure lists and lists are building blocks of code.

Each list is just a pair of parentheses with some elements inside and code is data inside list.
The first element of the list is normally the function and the rest of the elements are evaluated and passed to the function as its arguments.
List is a data type but they are also made up of code.

In the code above there is an example of the equals function with n and 1.

(if (= n 1)
1
(* n (fac (- n 1))))

n is the first argument of the call and is used in the condition. If true 1 is returned else the rest of the block is evaluated.

Unlike most languages, Clojure does not have an explicit else statement. It just evaluates the third element to if which is multiplying the number with the factorial of the number minus 1.
Clojure does not have an explicit return, the last expression in a function is used as the return value.

Lisp does not have a concept of operators being different from functions so operators are just functions that compares its arguments.

The environment set up to code in clojure was another challenge

1. IDE
I decided to use Light Table as IDE after reading the stackoverflow post since I was planning to use ClojureScript
http://stackoverflow.com/questions/4248171/choosing-an-ide-editor-for-clojure-coding . It helps greatly with writing Clojure making sure the parentheses are rightly used.

Light Table can be downloaded from http://lighttable.com/

Ctrl/Space open the commands available and type in inst and pick “Instarepl: Open a clojure instarepl” to open REPL.
Instarepl

The factorial function run and evaluated through Light Table IDE.

REPL

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s