Functions in Clojure: Day 3

Abid Uzair
Clojure Days
Published in
2 min readDec 6, 2017

Let’s dive into functions in Clojure, but before that here’s an interesting screenshot for all you functional folks:

Slide from @ScottWlaschin ‘s talk on FP “patterns”

Cool, Right? Okay so, Functions in Clojure behave like operators just like +, *. Function calls have syntax which is quite similar to how operations are performed: opening parenthesis, operator, operands, closing parenthesis.

;; Function call
user=> (function-name [& args])

Clojure treats functions as values like you treat numbers or strings. This flexibility allows you to pass functions as arguments to other functions. And not just that, you can also return a function from a function.

Functions that can either take a function as an argument or return a function are called higher-order functions.

Some well known higher-order functions are map , reduce , filter , remove ,iterate etc.

;; Defining a function which returns the square of a number
user=> (defn square-me [arg] (* arg arg))
;; map function creates a new list by applying square-me function to ;; each member of the collection
user=> (map square-me [2 3 5 7])
;; [4 9 25 49]

map allows you to generalize the process of transforming a collection by applying a function—any function—over any collection.

Another key point about function calls which I would like to highlight is that Clojure evaluates all function arguments recursively before passing them to the function. Did you get that ? I doubt, no worries. Let me give you a step by step approach of how function arguments are evaluated from Clojure brave:

;; sub forms (inc 199) and (/ 100 (- 7 2)) are passed as arguments ;; to + functionuser=> (+ (inc 199) (/ 100 (- 7 2))) user=> (+ 200 (/ 100 (- 7 2))) ; evaluated "(inc 199)"user=> (+ 200 (/ 100 5)) ; evaluated (- 7 2)user=> (+ 200 20) ; evaluated (/ 100 5);; 220
;; All sub-forms are evaluated first before applying the + function

Hope you liked this article. If you have any ideas or suggestions do comment down below. Next up, I shall be discussing about defining functions, what are special forms.

Source: Chapter 3 Do Things: A Clojure Crash Course

Thanks for reading!

I ❤️Clojure

--

--

Abid Uzair
Clojure Days

Currently empowering the person closest to me. Long term plan is to bend the universe for good. Kinda like changing the world one person at a time.