Clojure-snips: Defining Functions in Clojure

Let’s look at the various ways in which functions can be defined.

Defining an anonymous function can be done as below. The below defines a function which multiplies something with 3.

#(* % 3)

If you run the above in a REPL then you won’t see anything meaningful. To get something meaningful try something like

(map #(* % 3) [1 2 3])  

You will get (3 6 9). How did it happen? Map takes a function and sequence as arguments and applies the function to all elements of seq and returns a list as result. Makes sense? No? Try to look at this.

Defining functions seems scary. Right? It’s not. There are easier ways to create functions in Clojure.

A simple way to define functions which just does nothing but returns a String is as below

(fn [a] (* a 3))

So why did I start with scary stuff? Because it’s useful sometimes when passing around and I like to be scary.

Clojure has a way to define multiple versions of functions like

(defn tmp
  ([] tmp "a")
  ([a] (str a))

You can call above with 0 or 1 arguments. It’s a nice way to do polymorphism.


One thought on “Clojure-snips: Defining Functions in Clojure

  1. Pingback: Writing about Clojure | ansh bansal

Leave a Reply

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

You are commenting using your 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