Introductory Clojure Presentation
-
Upload
jacquelyn-victoria -
Category
Software
-
view
259 -
download
0
Transcript of Introductory Clojure Presentation
The Clojure Programming Language
CS
571 Program
ming Languages
Brian GracinJenny PawlakJacquelyn S Victoria
90 Second Overview…..Clojure is…..
- A dialect of Lisp- General purpose language- Emphasizes functional programming- Runs on the Java Virtual Machine- Designed for Concurrency- Used in industry -- CapitalOne, Amazon, Facebook, Oracle
Simplicity“We suffer from so much incidental complexity in traditional OO languages, both syntactic and semantic, that I don’t think we even realise it anymore. I wanted to make ‘doing the right thing’ not a matter of convention and discipline, but the default. I wanted a solid concurrency story and great interoperability with existing Java libraries,.” -Rich Hickey, creator of Clojure
Rich Hickey, Clojure, Benevolent Dictator for Life
CLOJURE:- First Available: 2007- Latest Stable Release: 1.8 January 19, 2016
Why JVM?● Familiar - run just like Java apps● Use some familiar Java objects● Many available libraries● Established track record ● Now open-sourced.
http://www.braveclojure.com/java/ (Chapter 12)clojure.org/about/rationale
What are Clojure’s Characteristics?● Functional - succinct, understandable, reusable● Defaults to Immutability
○ Simplifies reasoning and testing○ Easier to share objects○ Thread safe
● but allows mutability!● Code-as-Data (Homoiconicity)● Syntactic Abstraction
Immutable objects are always thread safe.
—Brian Goetz, Java Concurrency in PracticeThe Joy of Clojure Chapter 6.
ExamplesHomoiconicityCode written in the language is encoded as data structures that the language has tools to manipulate
Syntatic Abstraction
Permits the definition of new language constructs whose meaning can be understood in terms of static translation into the core language.As Data:
As Code.
LISP
Java
functional
Java’s Librariesiteration
interfaces
Immutable datatypes
Lazy evaluation
Clojure
TruthinessWhat is truthy?
● true● 1● (= 1 1)● 0● “False”● []● Literally any value but false or nil
What is falsey?
● false● nil● (= 3 1)
Nil Punning: Handling Clojure’s empty sequences that are Truthy
Every[thing] is "true" all the time, unless it is nil or false.
—Brian Goetz, The Joy of Clojure
Clojure Data Structures● They are immutable by default● Support metadata● Implement java.lang.Iterable● Implement the read-only part of java.util.Collection
http://clojure.org/reference/data_structures
Data Collection Types - Part 1
ListsSingly linked listsFirst item in calling positionHeterogeneous elements
Compare to Haskell:Homogeneous lists
VectorsSimply evaluate each item in order.Quick look-up timesHeterogeneous elementsNo calling position
Data Collection Types - Part 2
MapsMaps store unique keys and one value per key (dictionaries and hashes)
Two types:
1. Hashed: key has hashCode, equals2. Sorted: implement Comparable
SetsStore zero or more unique items
Some Mutable Data Structures!
AtomsManaged shared synchronous independent state
RefsTransaction referencesSafe shared use of mutable storage Require SW transactional memory system
AgentsIndependent, asynchronous change of individual locationsOnly allow change due to an action
VarMutable storage locationCan be dynamically rebound per threadEnsure safety through thread isolation
FunctionsFirst Class
Created on demandStored in a data structurePassed as an argumentReturned as a value
Higher-OrderTakes one or more function argsReturns function as result
Pure FunctionsALWAYS return same resultNo observable side effects
(defn[arg1 arg2]
(;function code))
def or defn?
● Both bind a symbol or name ● def is only evaluated once● defn is evaluated every time it is called
Quick ComparisonHaskell:
average numbers = (fold (+) (numbers) ) / (length(numbers))
Clojure:
(defn average [numbers] (/ (reduce + numbers) (count numbers)))
Quick ComparisonHaskell:
fact x = if x == 0 then 1 else x * fact(x-1)
Clojure:
(defn factorial [n] (if (= n 0) 1 (* n (factorial (dec n)))))
Code example
https://rosettacode.org/wiki/Palindrome_detection#Clojure
Higher-Order FunctionsMap
>(map * [1 2 3 4] [5 6 7 8])(5 12 21 32)
Reduce
>(reduce max [0 -3 10 48])48
Comp
((comp str - +) 4 5) is equivalent to (str ( - ( + 4 5)))
Partial
(defn add10 (partial + 10))>(add10 3)13>(add10 3 4 8)25
Macros(defmacro infix
[infixed](list (second infixed)
(first infixed) (last infixed)))
>(1 + 2)error
>(infix (1 + 2))3
Java InteropAccessing member functions
>(.toUpperCase "fred")
"FRED"
>(Math/pow 2 4)
16
( proxy [class-and-interfaces] [args] fs+)
ConcurrencyDoseq
Do over a sequence
Dosync
Do all or nothing
Future
Generate a thread
Delay
Bind function but don’t evaluate
Promise
Create a binding with no value
Clojure Shortcomings:● Dynamic type checking● Doesn’t scale well: code size, team size, time elapsed● Startup time● If JVM is not a good solution, then Clojure isn’t either
○ Systems programming limitations○ Real-Time
http://martintrojer.github.io/beyond-clojure/2016/04/19/beyond-clojure-preludehttps://www.quora.com/What-is-clojure-bad-at
Clojure in IndustryThe Boeing 737 MAX Onboard Maintenance Function is 32,000 lines of Clojure.
First time Clojure used in aircraft software.
One of the largest code bases to date.
When to choose Clojure?Handle large amounts of data with significant hardware limitations.
When you want more concise code, easier to test and debug.
Easier to get over 90% coverage with unit testing.
When JVM or CLR can be used.
Clojure developers are the happiest developers
From an analysis of Reddit comments,
http://www.itworld.com/article/2693998/big-data/clojure-developers-are-the-happiest-developers.html
Online Resources/TutorialsClojure.org
Clojuredocs.org
Clojure-doc.org
Clojure-by-example
ClojureTV (Youtube channel)
Clojure for the Brave and True
Further InfoThe Joy of Clojure
Book by Chris Houser and Michael Fogus
Clojure Programming
Book by By Chas Emerick, Brian Carper, Christophe Grand
Simple Made Easy
Video by Rich Hickey