SlideShare a Scribd company logo
Functional Programming
with
Lucy Fang
@crushoncode
Imperative
OOP
Declarative
Functional
Programming paradigms
A comparison...
Object-oriented Functional
The HOW
How to perform tasks and how to track changes
in state
The WHAT
What information is desired and what
transformations are required
State changes are important Immutable state and data structures
Loops, conditionals, and method calls
Order of execution is important.
Function calls and managing loops through
recursion.
Instances of structures or classes Functions as first-class objects and data
collections.
Functional programming with clojure
What is Clojure?
● Dialect of the Lisp programming language
(+ 1 2)
● Hosted language running on the JVM (java virtual machine)
● Interoperable with the host language
● Written like a data structure
Functional programming with clojure
Basic Clojure Syntax
Define a value or data e.g. (def name “value”)
Define a function e.g. (defn functionName [argument] (behavior))
Binding a value e.g. (let [value])
Collections:
(list 1 2 3) => ‘(1 2 3)
(vec ‘(1 2 3) => [1 2 3] //similar to an array, zero indexed
(set ‘(1 2 1) => #{1 2} // set of unique values
(map + [1 2 3] [4 5 6]) => (5 7 9)
First-class functions
● Treats functions as values so you can assign it to a variable, pass it to other
functions, store it in data structures e.g arrays, lists
● Can be used in higher-order functions - takes functions as arguments or
returns a function as a result
● Constructed at runtime
Why is this useful?
● When your inputs are yet to be provided
● reduce unnecessary code
● Increase reusability - keep it DRY
First-class functions and higher order functions
(first class function)
=> (def double-it (number)
(fn [number] (* 2 number))
(higher-order function)
=> (map double-it [1 2 3])
=> (2 4 6)
(def double-it (partial * 2))
same as
(fn [number] (* 2 number)) or
#(* 2 %)
Function Composition
Takes a set of functions and returns a function that is the composition of those
functions.
(filter (comp not zero?) [0 1 0 2 0 3 0 4])
=> (1 2 3 4)
Functional programming with clojure
Pure function?
(def age 20)
(defn whats-my-age [name]
(str name “: ” age))
=> (whats-my-age “Prashant”)
=> “Prashant: 20”
Impure Pure
(def age 20)
(defn my-age [name]
(str name “:” age))
=> (my-age “Prashant”)
=> “Prashant:20”
Create another age...
(defn my-age [name]
(let [age 20]
(str name “:” age)))
=> (my-age “Prashant”)
=> “Prashant:20”
Libraries
(:import java.util.Date)
(defn race-complete [racer-name]
(str race-name “ finished on "(java.util.Date.))
=> (race-complete “Prashant")
=> "Prashant finished on Sun Oct 01 10:03:59 BST 2017"
=> (race-complete “Prashant")
=> "Prashant finished on Sun Oct 01 10:04:48 BST 2017"
Almost a lottery scam!
(defn scratchie-lottery []
(if (= (rand) 3)
"Congrats! You’re a millionaire!"
"Hahaha your money is mine!"))
=> (scratchie-lottery)
=> "Hahaha your money is mine!"
Pure doesn’t always mean Idempotent
A pure function
- calling f(x) will give the same result no matter how many times you call
it. E.g. (defn add-1 [n] (+ 1 n)
An idempotent function
f(f(x)) is the same as f(x).
E.g.
(clojure.string/upper-case (clojure.string/upper-case “hello”)) => “HELLO”
(float (float 2))
Why are pure functions useful?
● when given the same input, will always return the same output and does not
have any observable side effect - you have CERTAINTY!
● makes testing much easier - we have less set up as we simply give it the
input and assert on the output e.g. no need for a payment gateway
● they can be run anywhere, when do you find you are copying the code over?
A value is something that doesn’t change.
20 is 20.
1 January 2017 is just that.
$5 doesn’t become $10.
My favorite fruits are bananas and cherries
(hmmmm….but not together).
What if my favorite fruit is now figs?
Well it will be a different set.
An identity with a state whose value is a value
at a point in time.
Functional programming with clojure
Immutability - Persistent data structures
(list 1 2 3) => ‘(1 2 3)
(vec ‘(1 2 3) => [1 2 3] //similar to an array, zero indexed
(set ‘(1 2 1) => #{1 2} // set of unique values
(map + [1 2 3] [4 5 6]) => (5 7 9)
Memory is shared
So what if we do need to change state?
● Memory state can be shared readily between threads which makes
concurrency easier
● Software transactional memory (STM) supports sharing of changing state
between threads in a synchronous and coordinated manner.
● Vars are for when you need to store something on a per-thread basis. If you
have a multi-threaded program and each thread needs its own private state,
put that state in a var.
Coordinated Uncoordinated
synchronous Ref (STM) atoms
asynchronous - agents
Recursion vs tail recursion
Traditional recursive
(defn factorial [n]
(if (zero? n)
1
(* n (factorial (dec n)))))
You don’t get the result of your
calculation until you have returned from
every recursive call. Generates a new
stackframe for each call.
Tail recursion
(defn factorial [n]
(loop [count n
result 1]
(if (pos? count)
(recur (dec count) (* result count))
result )))
Processing occurs before recursive call.
Reuse existing stackframes.
Compare on the call stack
Traditional recursive Tail recursion
(factorial 5) : 5 * _
(factorial 4) : 4 * _
(factorial 3) : 3 * _
(factorial 2) : 2 * _
(factorial 1) : 1 * _
(factorial 0) : 1
(factorial 5)
1
1
2
6
24
(factorial 5) = 120 (factorial 5) =
(loop 5 0)(loop 4 5)(loop 3 20)(loop 2 60)(loop 1 120)
120
count
n
Lazy evaluation
● Only return a value when necessary “call-by-need”
● Things are calculated not when they are defined, but when they are actually
needed.
● Maintain precision
● Optimise evaluation
Examples: ratios, lazy sequence such as range and repeat
TDD using midje
● Test driven development - Red/Green/Refactor
● Clean, tested, lean
● Midje - testing framework for clojure
Clojure resources
- Lots of resources
- Clojure documentation
- https://www.braveclojure.com/
- https://clojure.org/community/books
- Clojure koans
- tryclj.com/ online REPL
- https://clojure.org/api/cheatsheet
(def time-to “code!”)

More Related Content

What's hot (20)

PPTX
Keywords of java
Jani Harsh
 
PDF
JavaProgrammingManual
Naveen Sagayaselvaraj
 
PDF
The Ring programming language version 1.8 book - Part 25 of 202
Mahmoud Samir Fayed
 
PDF
The what over the how (another way on android development with kotlin)
Jose Manuel Pereira Garcia
 
PPTX
Operator overload rr
Dhivya Shanmugam
 
PDF
The Ring programming language version 1.5.1 book - Part 30 of 180
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.9 book - Part 27 of 210
Mahmoud Samir Fayed
 
PDF
Python lecture 05
Tanwir Zaman
 
PDF
TeraSort
Tung D. Le
 
PPTX
Image Recognition with Neural Network
Sajib Sen
 
PDF
Swift Tutorial 2
Jintin Lin
 
TXT
123
htmrk
 
PDF
Clojure functions examples
Jackson dos Santos Olveira
 
PDF
The Ring programming language version 1.5.2 book - Part 31 of 181
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.2 book - Part 21 of 84
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.7 book - Part 35 of 196
Mahmoud Samir Fayed
 
PDF
Quick python reference
Jayant Parida
 
PPTX
R programming
Pramodkumar Jha
 
PDF
7 Habits For a More Functional Swift
Jason Larsen
 
PPTX
Ppt on java basics
Mavoori Soshmitha
 
Keywords of java
Jani Harsh
 
JavaProgrammingManual
Naveen Sagayaselvaraj
 
The Ring programming language version 1.8 book - Part 25 of 202
Mahmoud Samir Fayed
 
The what over the how (another way on android development with kotlin)
Jose Manuel Pereira Garcia
 
Operator overload rr
Dhivya Shanmugam
 
The Ring programming language version 1.5.1 book - Part 30 of 180
Mahmoud Samir Fayed
 
The Ring programming language version 1.9 book - Part 27 of 210
Mahmoud Samir Fayed
 
Python lecture 05
Tanwir Zaman
 
TeraSort
Tung D. Le
 
Image Recognition with Neural Network
Sajib Sen
 
Swift Tutorial 2
Jintin Lin
 
123
htmrk
 
Clojure functions examples
Jackson dos Santos Olveira
 
The Ring programming language version 1.5.2 book - Part 31 of 181
Mahmoud Samir Fayed
 
The Ring programming language version 1.2 book - Part 21 of 84
Mahmoud Samir Fayed
 
The Ring programming language version 1.7 book - Part 35 of 196
Mahmoud Samir Fayed
 
Quick python reference
Jayant Parida
 
R programming
Pramodkumar Jha
 
7 Habits For a More Functional Swift
Jason Larsen
 
Ppt on java basics
Mavoori Soshmitha
 

Similar to Functional programming with clojure (20)

PPT
Clojure 1a
Krishna Chaytaniah
 
PDF
Get into Functional Programming with Clojure
John Stevenson
 
PDF
Fun with Functional Programming in Clojure - John Stevenson - Codemotion Amst...
Codemotion
 
PPTX
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
PDF
Clojure intro
Basav Nagur
 
PDF
Fun with Functional Programming in Clojure
Codemotion
 
KEY
Scala: functional programming for the imperative mind
Sander Mak (@Sander_Mak)
 
PDF
Thinking Functionally - John Stevenson - Codemotion Rome 2017
Codemotion
 
PDF
Thinking Functionally with Clojure
John Stevenson
 
PDF
Functional web with clojure
John Stevenson
 
PPTX
Functional Programming.pptx
KarthickT28
 
PDF
Functional Programming with Clojure
Carlo Sciolla
 
PDF
Stefan Kanev: Clojure, ClojureScript and Why They're Awesome at I T.A.K.E. Un...
Mozaic Works
 
KEY
The Joy Of Functional Programming
jasondew
 
PDF
Functional programming
ijcd
 
KEY
LISP: How I Learned To Stop Worrying And Love Parantheses
Dominic Graefen
 
PDF
Functional Go
Geison Goes
 
PDF
Thinking Functionally
Piyush Katariya
 
PDF
Functional Programming #FTW
Adriano Bonat
 
PPTX
Principles of functional progrmming in scala
ehsoon
 
Get into Functional Programming with Clojure
John Stevenson
 
Fun with Functional Programming in Clojure - John Stevenson - Codemotion Amst...
Codemotion
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
Clojure intro
Basav Nagur
 
Fun with Functional Programming in Clojure
Codemotion
 
Scala: functional programming for the imperative mind
Sander Mak (@Sander_Mak)
 
Thinking Functionally - John Stevenson - Codemotion Rome 2017
Codemotion
 
Thinking Functionally with Clojure
John Stevenson
 
Functional web with clojure
John Stevenson
 
Functional Programming.pptx
KarthickT28
 
Functional Programming with Clojure
Carlo Sciolla
 
Stefan Kanev: Clojure, ClojureScript and Why They're Awesome at I T.A.K.E. Un...
Mozaic Works
 
The Joy Of Functional Programming
jasondew
 
Functional programming
ijcd
 
LISP: How I Learned To Stop Worrying And Love Parantheses
Dominic Graefen
 
Functional Go
Geison Goes
 
Thinking Functionally
Piyush Katariya
 
Functional Programming #FTW
Adriano Bonat
 
Principles of functional progrmming in scala
ehsoon
 
Ad

Recently uploaded (20)

PDF
Rewards and Recognition (2).pdf
ethan Talor
 
PPTX
declaration of Variables and constants.pptx
meemee7378
 
PPTX
For my supp to finally picking supp that work
necas19388
 
PPTX
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
2nd Sight Lab
 
PDF
Which Hiring Management Tools Offer the Best ROI?
HireME
 
PDF
Best Software Development at Best Prices
softechies7
 
PDF
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
PDF
Automated Test Case Repair Using Language Models
Lionel Briand
 
PPTX
Android Notifications-A Guide to User-Facing Alerts in Android .pptx
Nabin Dhakal
 
PPTX
IObit Uninstaller Pro 14.3.1.8 Crack Free Download 2025
sdfger qwerty
 
PPTX
Iobit Driver Booster Pro 12 Crack Free Download
chaudhryakashoo065
 
PPTX
IDM Crack with Internet Download Manager 6.42 Build 41 [Latest 2025]
pcprocore
 
PDF
What Is an Internal Quality Audit and Why It Matters for Your QMS
BizPortals365
 
PDF
Code Once; Run Everywhere - A Beginner’s Journey with React Native
Hasitha Walpola
 
PDF
OpenChain Webinar - AboutCode - Practical Compliance in One Stack – Licensing...
Shane Coughlan
 
PPTX
CV-Project_2024 version 01222222222.pptx
MohammadSiddiqui70
 
PPTX
ERP Systems in the UAE: Driving Business Transformation with Smart Solutions
dheeodoo
 
PDF
Designing Accessible Content Blocks (1).pdf
jaclynmennie1
 
PPTX
Wondershare Filmora Crack 14.5.18 + Key Full Download [Latest 2025]
HyperPc soft
 
DOCX
Best AI-Powered Wearable Tech for Remote Health Monitoring in 2025
SEOLIFT - SEO Company London
 
Rewards and Recognition (2).pdf
ethan Talor
 
declaration of Variables and constants.pptx
meemee7378
 
For my supp to finally picking supp that work
necas19388
 
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
2nd Sight Lab
 
Which Hiring Management Tools Offer the Best ROI?
HireME
 
Best Software Development at Best Prices
softechies7
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Automated Test Case Repair Using Language Models
Lionel Briand
 
Android Notifications-A Guide to User-Facing Alerts in Android .pptx
Nabin Dhakal
 
IObit Uninstaller Pro 14.3.1.8 Crack Free Download 2025
sdfger qwerty
 
Iobit Driver Booster Pro 12 Crack Free Download
chaudhryakashoo065
 
IDM Crack with Internet Download Manager 6.42 Build 41 [Latest 2025]
pcprocore
 
What Is an Internal Quality Audit and Why It Matters for Your QMS
BizPortals365
 
Code Once; Run Everywhere - A Beginner’s Journey with React Native
Hasitha Walpola
 
OpenChain Webinar - AboutCode - Practical Compliance in One Stack – Licensing...
Shane Coughlan
 
CV-Project_2024 version 01222222222.pptx
MohammadSiddiqui70
 
ERP Systems in the UAE: Driving Business Transformation with Smart Solutions
dheeodoo
 
Designing Accessible Content Blocks (1).pdf
jaclynmennie1
 
Wondershare Filmora Crack 14.5.18 + Key Full Download [Latest 2025]
HyperPc soft
 
Best AI-Powered Wearable Tech for Remote Health Monitoring in 2025
SEOLIFT - SEO Company London
 
Ad

Functional programming with clojure

  • 3. A comparison... Object-oriented Functional The HOW How to perform tasks and how to track changes in state The WHAT What information is desired and what transformations are required State changes are important Immutable state and data structures Loops, conditionals, and method calls Order of execution is important. Function calls and managing loops through recursion. Instances of structures or classes Functions as first-class objects and data collections.
  • 5. What is Clojure? ● Dialect of the Lisp programming language (+ 1 2) ● Hosted language running on the JVM (java virtual machine) ● Interoperable with the host language ● Written like a data structure
  • 7. Basic Clojure Syntax Define a value or data e.g. (def name “value”) Define a function e.g. (defn functionName [argument] (behavior)) Binding a value e.g. (let [value]) Collections: (list 1 2 3) => ‘(1 2 3) (vec ‘(1 2 3) => [1 2 3] //similar to an array, zero indexed (set ‘(1 2 1) => #{1 2} // set of unique values (map + [1 2 3] [4 5 6]) => (5 7 9)
  • 8. First-class functions ● Treats functions as values so you can assign it to a variable, pass it to other functions, store it in data structures e.g arrays, lists ● Can be used in higher-order functions - takes functions as arguments or returns a function as a result ● Constructed at runtime Why is this useful? ● When your inputs are yet to be provided ● reduce unnecessary code ● Increase reusability - keep it DRY
  • 9. First-class functions and higher order functions (first class function) => (def double-it (number) (fn [number] (* 2 number)) (higher-order function) => (map double-it [1 2 3]) => (2 4 6) (def double-it (partial * 2)) same as (fn [number] (* 2 number)) or #(* 2 %)
  • 10. Function Composition Takes a set of functions and returns a function that is the composition of those functions. (filter (comp not zero?) [0 1 0 2 0 3 0 4]) => (1 2 3 4)
  • 12. Pure function? (def age 20) (defn whats-my-age [name] (str name “: ” age)) => (whats-my-age “Prashant”) => “Prashant: 20”
  • 13. Impure Pure (def age 20) (defn my-age [name] (str name “:” age)) => (my-age “Prashant”) => “Prashant:20” Create another age... (defn my-age [name] (let [age 20] (str name “:” age))) => (my-age “Prashant”) => “Prashant:20”
  • 14. Libraries (:import java.util.Date) (defn race-complete [racer-name] (str race-name “ finished on "(java.util.Date.)) => (race-complete “Prashant") => "Prashant finished on Sun Oct 01 10:03:59 BST 2017" => (race-complete “Prashant") => "Prashant finished on Sun Oct 01 10:04:48 BST 2017"
  • 15. Almost a lottery scam! (defn scratchie-lottery [] (if (= (rand) 3) "Congrats! You’re a millionaire!" "Hahaha your money is mine!")) => (scratchie-lottery) => "Hahaha your money is mine!"
  • 16. Pure doesn’t always mean Idempotent A pure function - calling f(x) will give the same result no matter how many times you call it. E.g. (defn add-1 [n] (+ 1 n) An idempotent function f(f(x)) is the same as f(x). E.g. (clojure.string/upper-case (clojure.string/upper-case “hello”)) => “HELLO” (float (float 2))
  • 17. Why are pure functions useful? ● when given the same input, will always return the same output and does not have any observable side effect - you have CERTAINTY! ● makes testing much easier - we have less set up as we simply give it the input and assert on the output e.g. no need for a payment gateway ● they can be run anywhere, when do you find you are copying the code over?
  • 18. A value is something that doesn’t change. 20 is 20. 1 January 2017 is just that. $5 doesn’t become $10. My favorite fruits are bananas and cherries (hmmmm….but not together).
  • 19. What if my favorite fruit is now figs? Well it will be a different set. An identity with a state whose value is a value at a point in time.
  • 21. Immutability - Persistent data structures (list 1 2 3) => ‘(1 2 3) (vec ‘(1 2 3) => [1 2 3] //similar to an array, zero indexed (set ‘(1 2 1) => #{1 2} // set of unique values (map + [1 2 3] [4 5 6]) => (5 7 9)
  • 23. So what if we do need to change state? ● Memory state can be shared readily between threads which makes concurrency easier ● Software transactional memory (STM) supports sharing of changing state between threads in a synchronous and coordinated manner. ● Vars are for when you need to store something on a per-thread basis. If you have a multi-threaded program and each thread needs its own private state, put that state in a var. Coordinated Uncoordinated synchronous Ref (STM) atoms asynchronous - agents
  • 24. Recursion vs tail recursion Traditional recursive (defn factorial [n] (if (zero? n) 1 (* n (factorial (dec n))))) You don’t get the result of your calculation until you have returned from every recursive call. Generates a new stackframe for each call. Tail recursion (defn factorial [n] (loop [count n result 1] (if (pos? count) (recur (dec count) (* result count)) result ))) Processing occurs before recursive call. Reuse existing stackframes.
  • 25. Compare on the call stack Traditional recursive Tail recursion (factorial 5) : 5 * _ (factorial 4) : 4 * _ (factorial 3) : 3 * _ (factorial 2) : 2 * _ (factorial 1) : 1 * _ (factorial 0) : 1 (factorial 5) 1 1 2 6 24 (factorial 5) = 120 (factorial 5) = (loop 5 0)(loop 4 5)(loop 3 20)(loop 2 60)(loop 1 120) 120 count n
  • 26. Lazy evaluation ● Only return a value when necessary “call-by-need” ● Things are calculated not when they are defined, but when they are actually needed. ● Maintain precision ● Optimise evaluation Examples: ratios, lazy sequence such as range and repeat
  • 27. TDD using midje ● Test driven development - Red/Green/Refactor ● Clean, tested, lean ● Midje - testing framework for clojure
  • 28. Clojure resources - Lots of resources - Clojure documentation - https://www.braveclojure.com/ - https://clojure.org/community/books - Clojure koans - tryclj.com/ online REPL - https://clojure.org/api/cheatsheet