Clojure Language Concepts

The post provides a description of some of key concepts and words used in Clojure.

Let

Let binds symbols to immutable values

(let [a 7
b  5]
(+ a b)
)

Let_Example

The bound symbols are available in lexical scope, i.e. a and b can’t be accessed outside.

Multi-Arity Function

Multi-arity functions  is  same as overloading methods in C# which means varying number of arguments can be passed to the same function name

(defn addNumber
([] (addNumber 2 3))
([a b] (+ a b)))
(addNumber) 5
(addNumber 20 30) 50

Arity_Example

Variadic arity Function
Variadic arity allows one version of a function with variable number of arguments.
It uses the  & symbol in parameters which means collects all remaining args

(defn concatString [a & b]
(print a b))
(concatString "I" "M" "N" "P")

Variadic Arity

Apply

Apply invokes function on arguments

(let [a 1
b 2
more '(3 4)]
(apply concatString a b more))

Apply

Apply can be used with operators also

(let [numbers '(1 2 3)]
(apply + numbers))

Let_apply

Dot

Allows to access properties

(.length "closure")

dot

Chaining Function using Clojure Sugar

Let’s say we need to get first name of the object employee. We might have to get full name of the employee before working out the first name.

Using C# the syntax can be something like

employee.getName().getFirstName()

In Clojure

 (.getFirstName (.getName employee))

The code in Clojure is not easy to read. Using Clojure Sugar (..) the code can be written as

(.. employee getName getFirstName)

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