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)

KEY
(map Clojure everyday-tasks)
Jacek Laskowski
 
PDF
Functional Programming with Groovy
Arturo Herrero
 
PPTX
Scala for curious
Tim (dev-tim) Zadorozhniy
 
PDF
Pune Clojure Course Outline
Baishampayan Ghose
 
PDF
Scala for Java Developers
Martin Ockajak
 
PDF
Monadologie
league
 
PPTX
ifelse.pptx
JananiJ19
 
PPTX
Introduction to python programming ( part-2 )
Ziyauddin Shaik
 
ODP
Introduction to R
agnonchik
 
PDF
Apache Spark - Basics of RDD & RDD Operations | Big Data Hadoop Spark Tutoria...
CloudxLab
 
PPTX
Flying Futures at the same sky can make the sun rise at midnight
Wiem Zine Elabidine
 
ODP
Scala ntnu
Alf Kristian Støyle
 
PPTX
Hello kotlin | An Event by DSC Unideb
Muhammad Raza
 
KEY
Functional programming in clojure
Juan-Manuel Gimeno
 
PPTX
Structure and interpretation of computer programs modularity, objects, and ...
bdemchak
 
PPTX
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Iterative Spark Developmen...
Data Con LA
 
PDF
Lecture 5: Functional Programming
Eelco Visser
 
PDF
[Greach 17] make concurrency groovy again
Alonso Torres
 
ZIP
Lisp Macros in 20 Minutes (Featuring Clojure)
Phil Calçado
 
PDF
(first '(Clojure.))
niklal
 
(map Clojure everyday-tasks)
Jacek Laskowski
 
Functional Programming with Groovy
Arturo Herrero
 
Scala for curious
Tim (dev-tim) Zadorozhniy
 
Pune Clojure Course Outline
Baishampayan Ghose
 
Scala for Java Developers
Martin Ockajak
 
Monadologie
league
 
ifelse.pptx
JananiJ19
 
Introduction to python programming ( part-2 )
Ziyauddin Shaik
 
Introduction to R
agnonchik
 
Apache Spark - Basics of RDD & RDD Operations | Big Data Hadoop Spark Tutoria...
CloudxLab
 
Flying Futures at the same sky can make the sun rise at midnight
Wiem Zine Elabidine
 
Hello kotlin | An Event by DSC Unideb
Muhammad Raza
 
Functional programming in clojure
Juan-Manuel Gimeno
 
Structure and interpretation of computer programs modularity, objects, and ...
bdemchak
 
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Iterative Spark Developmen...
Data Con LA
 
Lecture 5: Functional Programming
Eelco Visser
 
[Greach 17] make concurrency groovy again
Alonso Torres
 
Lisp Macros in 20 Minutes (Featuring Clojure)
Phil Calçado
 
(first '(Clojure.))
niklal
 
Ad

Recently uploaded (20)

PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PPTX
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
PPTX
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PDF
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PDF
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PPTX
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
Tally software_Introduction_Presentation
AditiBansal54083
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
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