1 Pro Tip
2 Workshop problem
Given a text file, let's find the n most common and uncommon words. Ignore certain stop words.Lesson taught: Data > Code.
Output:How to write your own
frequenciesfunction and introducing how to use
fnil is better than an
if form - telling computer what vs. how.
A better way to sort was shown by BG:
Introduction to threading macros to simplify series of function compositions.
Amazing how much has been covered and BG hasn't mention the
at all so far (although I'm using it).
juxtworking in my own
mainfunction - I was trying to call
juxtand messing things up, instead I should have just called the result of
The star at the end of a name is a convention which means it is an alternative version or slightly different version.
- Dispatch on an arbitrary function
- Ad-hoc hierarchies
Java is also single-dispatch because it can dispatch on only one factor - the type (i.e. the class and the arity of the method).
Hierarchies and type concepts are tied together in Java.
Example of how to do multimethods in Clojure:
::keyword is used to confine the keyword to the current namespace.
The argument is a dispatch function which should not have side-effects.
Since OS X is a derivative of Unix, use
So this means that
osx "derives the functionality" from
we are creating a hierarchy.
This is going to take some time to digest… the dispatch here is on a map which is the idiom in Clojure compared to dispatching on the class in Java.Introducing multiple dispatch by dispatching on both
:default to give a default multimethod implementation.
descendants to introspect the hierarchy.
prefers to handle when multiple ancestors match for a
Recommendation to read http://clojure.org/multimethods
Discussion on what is the difference between a class and a type? In Java, there is no difference. But they are actually orthogonal concepts.
So use a type to differentiate / switch behavior and we can use a simple map data structure or a keyword or any simple values in Clojure as a "type", instead of depending entirely on "classes" in traditional OOP languages. A class is a bag of data and behavior.
Taking duck-typing as an example, as long as a parameter matches some "behavior" (type), we can use that parameter regardless of what "class" it belongs to.
On the other side, a class can have many "types", for example, a vector can also behave as a collection and can behave as a sequence.Recommendation to read http://thinkrelevance.com/blog/2009/08/12/rifle-oriented-programming-with-clojure-2
Point is to keep data and functionality separate and not complect it into classes.
Multimethods are extensible, they are global and hence users of the code can extend the multimethod to more types.
Example of built-in print-method.
4 Protocols & Types
Introduction to protocols & types: How do you extend a third-party library without access to it's source code?
In OOP languages, you can create a new class and subclass existing third-party class and interoperate bidirectionally.
In FP languages, you can create a new method and make it work on existing third-party classes.
You have to choose either one in traditional OOP and FP languages.
This is called the Expression Problem.In current languages, the solution is usually monkey-patching (think of
find_by*methods in Rails ActiveRecord) which can be full of surprises and brittleness.
Discussion on how you can use visitor pattern in Java to add new
functionality on top of existing classes, but you lose identity - you
Student but you get
In Clojure, you can do both, in a clean manner.
We can use multimethods but the limitation is that it is global.
Multimethods have the advantage of multiple dispatch. Protocols are single-dispatch on type.
The separation between types and behaviors in Clojure enables the concept of protocols.
Protocols can be confined to one namespace. Multimethods are global.
Example uses records - records behave like a map but has a type (identity) attached to it.
extendunderneath which is just associating a type with a protocol with a map data structure of function names to implementations.
You can check if a type
extends? a protocol or an object
reify - reification means given an abstraction, create a
concretion. It allows you to create anonymous implementations of any
You can use lexical closures inside a function and returns an object of anonymous type (a dynamic implementation) that satisfies a protocol.
reify is it cannot instantiate classes, it can only
instantiate protocols and interfaces. For classes, you can use
which is mainly used for Java interoperability.
Advantage of protocol is that you can group functions and check if a type extends that protocol. That is the difference from multimethods.Example of how to use protocols to create mixins with example of
IOFactoryimplementations in the Clojure source code - data all the things!
Internally, Clojure uses interfaces and ClojureScript uses protocols. In future, Clojure will internally switch to protocols as well.
Handle state properly and you'll get concurrency for free. Get the basics right.
BG gave example of his experience in Cleartrip.com about state and mutability.
In Clojure, identity and value are separated.
- immutable data in a persistent structure
- series of causally related values over time
- identity at a point in time
|synchronous /||refs / stm||-|
- update by function application
- readers require no coordination
- readers never block anybody
- writers never block readers
@reader macro to dereference a reference type and get the value behind it.
Vars are special because they are deref-ed automatically.STM-related functionality like
commutehave to be in a
dosyncform (transaction). vars can be rebound:
In concurrency, there is at least one resource being shared.
All along, we have multiple processes running on a single CPU core because we have concurrent processes, i.e. there is scheduling. Concurrent code can be sequential or parallel.
Parallelism is about running multiple processes at the same time across multiple CPU cores. Parallelism is highest when there are no shared resources.
If code is written properly w.r.t. concurrency, you will get parallelism for free.
Proper code written can run as fast as possible on a single-core machine or a multiple-core machine. But non-concurrent code (use locks, etc.) can run as fast as possible on a single-core machine but will not increase in performance on a multiple-core machine.
DSLs via MacrosMacros are functions that run at compile-time that will generate data which will be treated as code at run-time.
- Syntax quote (back-tick)
- Unquote (tilde)
- Unquote splicing (tilde and at-symbol)
- Use the contents of the list directly
- Variable capture
If you want to create an
unless form which is semantically a boolean
opposite of the
when form (an
if form with only the
else form), you cannot use a function because the parameters
will be evaluated before calling the function, so you will need a macro
Using a hash at the end of a new var name inside a macro means a
universally unique name is generated so that there are no name clashes
with other code that the macro expansion is part of. It is same as
gensym function manually.
There is a Clojure built-in that does the same as
unless but it is
given a better name -
Example of a recursive macro:
Introducing a longer example of using macros and functions to create a quite complex DSL. And finally generated XML out of it! Wow.
8 Not Covered
- Reducers framework
- a lot more
9 End Notes
- Great Clojure Videos by Rich Hickey
@swaroopch Thanks for blogging this.
@swaroopch great post. Missed the clojure class in pune. Sounds amazing. Wishing for a delhi one @ghoseb
@swaroopch Thank you for the posts. And meeting you was a pleasure as always.
Experienced mind-expanding #clojure immersion thanks to the awesome workshop by @ghoseb. Gr8 wrap-up by @swaroopch: http://t.co/QzqEg3eKwA