You are on page 1of 52

Functional Programming

Prepared By
Ms.Himabindu Sri
Ms.Afreen Fatima Mohammed
Ms.Deepika
Clojure

Unit – No-5
Objectives
•Importance of Clojure
•Clojure-an evolution of LISP
•Working of Read Eval Print Loop- Clojure’s interactive programming environment
•Know Keyword, Vectors, list, Macros and Syntax quote
•Identity, Value and State in Clojure
•Concurrent Programming in Clojure
•Know the Concurrent programming Problem and design solution
•Understand atomic power, working of Agent and Ref
Importance of Clojure
• Designed for concurrent programming
• Performance is closer to Java than to Python
• Access to Java from Clojure, and Clojure from Java, is easy, wrapper-free, and fast
• A Lisp dialect
• Dynamically typed
Getting Clojure: Why Lisp Still Matter

• Clojure- a new evolution of Lisp


• Lisp is the second oldest high-level programming language
• Read Eval Print Loop or REPL- Clojure’s interactive programming environment
• Uses Vectors, Keywords and Macros
REPL
• Run “hello, world” in REPL
• Create a function say-hello
Examples
• Add two numbers

•Evaluate the integer 1 and string "foo" in the REPL


• Evaluate expression

• To turn-off Evaluation
Keywords
• Are prepended with a colon
Vectors
• Created by placing the elements of the vector inside of square brackets
• Create a vector and name it some-keywords

• Use first to get the first element of a vector


• Use read-string to read in a new vector and name it some-more-keywords
List
• Is a singly linked list
• Create a list in REPL

• Use = to check whether the two lists are equivalent or not


• Create list with three elements: the symbol + and the integers 21
and 21

• Use first function to get the first element

• Function calls are evaluation rule for lists

• Evaluating funky-looking-list
Macros
• Special kind of function
• Takes a piece of data that represents code known as a form
• Transforms one form into another before Clojure’s compiler compiles it
• Does not evaluate its arguments
• Macro function make-printer is created

• Use Macro make-printer to create a function named foo


• Expand macro using macroexpand-1
Syntax quote
• Represented by a single backtick
• Turns evaluation back on inside of it using unquote, represented by a tilde

• make-printer rewritten using syntax quote


• defn expands to def and fn
Identity, Value, and State in Clojure

• Object Oriented Model


• Clojure Model
• Persistent Data Structures
• Managed Reference Types
Object-Oriented Model
• Computer memory consists of a series of eight memory cells, each of
which holds a bit of information
• Every cell has an address, which represents a place
• If any change in a place occurs, any notion of what was there in the
past is lost
• Many object references may refer to the same place
• If an object is modified through any of those references, all of the
references may eventually see the modification

References: me, personOne, aGuy

•By changing name and adress, old name and address would be lost
Clojure Model
• Defines Value, Identity and State
• Value
An immutable piece of data, or a composite of immutable pieces of data
• Identity
An entity that’s associated with a series of values over time
• State
Is just the value of an identity at a point in time
Persistent Data Structures

• Preserves its previous version when it’s modified, making it appear


to be immutable
• Uses Structural sharing technique to avoid copying all of the data in
the data structure
• Examples: Maps, vectors, and sets
Persistent Map
• Create a map by putting a series of key-value pairs between curly braces

• Map referred by mike is immutable, cannot be modified directly

• Use assoc to create a new, immutable map


• Assoc function takes a map-like datastructure and a variable number of key-
value pairs, and associate them with map

• If the keys have values existing in the map, they are overwritten
Managed Reference Types
• Is between an immutable data structure and the references to it and manage state
changes
• All of the references being managed point at the latest value for a given identity
• To see a value, the reference that points to it must be de-referenced
• De-referencing returns the state that the reference refers to, which captures it at
the point in time it was de-referenced
Types of managed references
• Atoms
Manage independent state synchronously

• Agents

• Refs
Atom
• The swap! function takes an atom, a function to call on the value it refers to, and
additional arguments for the function
• The swap! function then runs the passed-in function on the value of the atom and
the additional arguments, returning the new value
• Create an add-to-int-atom, which adds an integer to the atom
• Use add-to-int-atom to add the number 42 to the number that the atom refers to

•To de-reference the atom, use the @ symbol

•De-reference it into int-atom-snapshot


• Create another reference, another-int-atom-reference, which
refers to the same managed reference that int-atom does
• Results of the addition when we de-reference both int-atom and
another-int-atom-reference

• The snapshot remains unchanged


Concurrent Programming

• Multiple processes, or threads run in parallel


• Coordinating access to shared resources is difficult
A "Simple" Concurrent Programming Problem

Output:
Solution
• Use Java’s locking mechanisms to protect the counter variable to ensure that only
one thread can access the counter at a time, and that any modifications made to it
are visible when the lock is relinquished
• Another higher-level solution is the one that we demonstrated using AtomicInteger
• The AtomicInteger class provides an incrementAndGet, which atomically
increments an internal counter, ensuring that no thread can see it in an inconsistent
state
• Two main downsides to the AtomicInteger solution are that it can only be used for
integers, and it can only deal with coordinating changes to a single object
Clojure’s Solution
• Use Clojure’s immutable data structures, managed reference types, and software
transactional memory system combine to provide a model that’s both high level
and much easier to use than locking concurrency
Atomic Power
• Atoms are good for managing state that’s independent and to which we want to
make synchronous change
• The swap! function applies the passed in function to the value wrapped by the
atom, swaps the old value for the new one, and returns it
• Create a simple atom counter, and a function to increment it

• Use @ to de-reference an atom, or any of Clojure’s managed references


• Rewriting original Java example to something similar in Clojure,
which takes advantage of atoms

• Running concurrent-atom-modification sets our counter to the correct value


Agent
• Manage changes to independent state, but they’re designed to do so in an
asynchronous way
• Use the send function
• It takes an atom to modify
• Operations are queued if necessary and applied to the agent serially
• An atom version of counter and a function to increment it is created
• Calling increment-agent-counter returns a reference to the agent
Ref
• Used when to make coordinated changes across more than one data structure
• Example: To keep track of television series and episodes
• An episode of a series is represented as a map with an id, a name, and a nested
map
• The nested series has a series id and name
• Create a couple of refs to hold maps

• Episodes are added using assoc

• Uses alter which takes a reference, function, and arguments


• alter is called inside of a transaction
• To create a transaction, wrap calls to alter inside of dosync
• This acts like a database transaction, and it turns our multiple calls to alter into one
atomic unit
• If one thread was to modify either map while another was in the process of doing
so, one thread would win and its transaction would commit
• The other would roll its transaction back and try it again
• Create few test episodes and add them to the system
Summary
•Learn the importance of Clojure
•Clojure-an evolution of LISP
•Working of Read Eval Print Loop- Clojure’s interactive programming environment
•Understand Keyword, Vectors, list, Macros and Syntax quote
•Identity, Value and State in Clojure
•Concurrent Programming in Clojure
•Know the Concurrent programming Problem and design solution
•Understand atomic power, working of Agent and Ref
References
• [1]. Michael Swaine and the PragPub writers, “Functional Programming: A PragPub
Anthology- Exploring Clojure, Elixir, Haskell, Scala and Swift”, The Pragmatic
Programmers

You might also like