Fun with Functional Programming in ClojureCodemotion
"Fun with Functional Programming in Clojure" by John Stevenson.
Clojure is a simple, powerful and fun language. With a small syntax its quick to learn, meaning you can focus on functional design concepts and quickly build up confidence. There are also a wide range of Clojure libraries to build any kind of apps or services quickly. With a focus on Immutability, Persistent data structures & lazy evaluation, you will quickly feel confident about the Functional Programming (FP) approach to coding. Discover Clojure in action as we write & evaluate Clojure using the REPL (interactive run-time environment), giving instant feedback on what the code is doing.
This introduction to Clojure was given to the Utah Java Users Group Aug. 15. It's main focus was on Clojure's time model and how the design of Clojure separates (decomplects) many concepts which are all implemented onto of Objects in Java, and other OO languages. This is the abstract for the original talk:
Tony Hoare famously said "There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult." Clojure is a functional Lisp that targets, among other platforms, the JVM and strives to enable the former approach to building software.
In its pursuit of simplicity Clojure encourages the use of pure functions, sequence abstractions which allow for lazy and parallel processing of data, persistent (immutable) data structures, and a novel way of dealing with state as a succession of values. While these concepts may sound intimidating for those unfamiliar with functional programming, they are actually less complicated than many programming constructs that programmers use everyday.
This talk will cover these concepts and the motivation behind them. You will learn the basics of Clojure programming and will be given a taste of what developing an application in Clojure is like.
There is an increasing interest in functional programming from Java developers and the organisations in which they work. For many companies the challenge now is how to make use of the competitive advantage of functional programming. For developers, how do you adapt your mindset to this newly reimagined paradigm? Through the use of examples and a modular approach to design, Clojure made simple will show how developers can be productive quickly without a major change to their current development life-cycle. We will also cover the Clojure build process, tools and exciting projects out there.
Fun with Functional Programming in ClojureCodemotion
"Fun with Functional Programming in Clojure" by John Stevenson.
Clojure is a simple, powerful and fun language. With a small syntax its quick to learn, meaning you can focus on functional design concepts and quickly build up confidence. There are also a wide range of Clojure libraries to build any kind of apps or services quickly. With a focus on Immutability, Persistent data structures & lazy evaluation, you will quickly feel confident about the Functional Programming (FP) approach to coding. Discover Clojure in action as we write & evaluate Clojure using the REPL (interactive run-time environment), giving instant feedback on what the code is doing.
This introduction to Clojure was given to the Utah Java Users Group Aug. 15. It's main focus was on Clojure's time model and how the design of Clojure separates (decomplects) many concepts which are all implemented onto of Objects in Java, and other OO languages. This is the abstract for the original talk:
Tony Hoare famously said "There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult." Clojure is a functional Lisp that targets, among other platforms, the JVM and strives to enable the former approach to building software.
In its pursuit of simplicity Clojure encourages the use of pure functions, sequence abstractions which allow for lazy and parallel processing of data, persistent (immutable) data structures, and a novel way of dealing with state as a succession of values. While these concepts may sound intimidating for those unfamiliar with functional programming, they are actually less complicated than many programming constructs that programmers use everyday.
This talk will cover these concepts and the motivation behind them. You will learn the basics of Clojure programming and will be given a taste of what developing an application in Clojure is like.
There is an increasing interest in functional programming from Java developers and the organisations in which they work. For many companies the challenge now is how to make use of the competitive advantage of functional programming. For developers, how do you adapt your mindset to this newly reimagined paradigm? Through the use of examples and a modular approach to design, Clojure made simple will show how developers can be productive quickly without a major change to their current development life-cycle. We will also cover the Clojure build process, tools and exciting projects out there.
From Java to Parellel Clojure - Clojure South 2019Leonardo Borges
Java still ranks at the top of the TIOBE index. The JVM is a trusted platform which has stood the test of time and is used widely to develop complex, reliable and high performing systems. By choosing to target the JVM, Clojure can leverage all of its power while bringing new ways of writing reliable software into the mix. But why should a Java developer care?
In this talk we will examine the main differences between Java and Clojure, pointing out new patterns and tools and finally ending with a discussion of the concurrency and parallelism abstractions provided by Clojure.
By the end of this talk you will have developed an understanding of Clojure’s fundamental building blocks for writing concurrent applications.
JavaOne 2013 - Clojure for Java DevelopersJan Kronquist
The fact that Clojure is a dialect of Lisp makes it feel completely alien to Java developers, and they miss the opportunity to learn this dynamic and functional programming language for the JVM. Clojure’s focus on immutability makes it very useful for concurrency. This presentation introduces Clojure in a way that feels natural to Java developers. By seeing how well Clojure interoperates with Java, you will learn how to take advantage of this wonderful language and still use all the frameworks and features of the JVM.
This was a presentation I gave at the 17th Tcl Conference, in Oakbrook Terrace, IL, in 2010. It describes some of the more sophisticated things that it is possible to do with the new Tcl object system, TclOO.
A very brief overview of the Clojure language. The majority of the presentation is in GIT revision history available from the GitHub link on the last slide:
http://github.com/larrytheliquid/buzzer
Clojure is a new language that combines the power of Lisp with an existing hosted VM ecosystem (the Java VM). Clojure is a dynamically typed, functional, compiled language with performance on par with Java.
At the heart of all programming lies the need for abstraction, be it abstraction over our data or abstraction over the processes that operate upon it. Clojure provides a core set of powerful abstractions and ways to compose them. These abstractions are based in a heritage of Lisp but also cover many aspects of object-oriented programming as well.
This talk will examine these abstractions and introduce you to both Clojure and functional programming. Attendees are not expected to be familiar with either Clojure or FP.
From Java to Parellel Clojure - Clojure South 2019Leonardo Borges
Java still ranks at the top of the TIOBE index. The JVM is a trusted platform which has stood the test of time and is used widely to develop complex, reliable and high performing systems. By choosing to target the JVM, Clojure can leverage all of its power while bringing new ways of writing reliable software into the mix. But why should a Java developer care?
In this talk we will examine the main differences between Java and Clojure, pointing out new patterns and tools and finally ending with a discussion of the concurrency and parallelism abstractions provided by Clojure.
By the end of this talk you will have developed an understanding of Clojure’s fundamental building blocks for writing concurrent applications.
JavaOne 2013 - Clojure for Java DevelopersJan Kronquist
The fact that Clojure is a dialect of Lisp makes it feel completely alien to Java developers, and they miss the opportunity to learn this dynamic and functional programming language for the JVM. Clojure’s focus on immutability makes it very useful for concurrency. This presentation introduces Clojure in a way that feels natural to Java developers. By seeing how well Clojure interoperates with Java, you will learn how to take advantage of this wonderful language and still use all the frameworks and features of the JVM.
This was a presentation I gave at the 17th Tcl Conference, in Oakbrook Terrace, IL, in 2010. It describes some of the more sophisticated things that it is possible to do with the new Tcl object system, TclOO.
A very brief overview of the Clojure language. The majority of the presentation is in GIT revision history available from the GitHub link on the last slide:
http://github.com/larrytheliquid/buzzer
Clojure is a new language that combines the power of Lisp with an existing hosted VM ecosystem (the Java VM). Clojure is a dynamically typed, functional, compiled language with performance on par with Java.
At the heart of all programming lies the need for abstraction, be it abstraction over our data or abstraction over the processes that operate upon it. Clojure provides a core set of powerful abstractions and ways to compose them. These abstractions are based in a heritage of Lisp but also cover many aspects of object-oriented programming as well.
This talk will examine these abstractions and introduce you to both Clojure and functional programming. Attendees are not expected to be familiar with either Clojure or FP.
Talk about DSL, How to write DSL in Clojure, How to use Instaparse (simplest library for parsing grammars) and how we use Clojure and Instaparse in Zoomdata
Presentation to a combined meetup of Bay Area Lisp and Bay Area Clojure groups. Presented three Clojure projects at BackType:
Cascalog - Batch processing in Clojure
ElephantDB - Database written in Clojure
Storm - Distributed, fault-tolerant, reliable stream processing and RPC
The talk will compare Cascalog, fully-featured data processing and querying library on top of Hadoop, and Sparkling – A Clojure API for Apache Spark. How both of these compare in terms of performance and code complexity for Big Data processing and why you shouldn’t be writing MapReduce jobs in plain Hadoop API.
JS Lab`16. Роман Лютиков: "ClojureScript, что ты такое?"GeeksLab Odessa
12.3.16 JS Lab.
Upcoming events: goo.gl/I2gJ4H
Сегодня уже в порядке вещей писать на языках компилируемых в JavaScript. В свете возрастающей популярности функционального программирования разработчики активно смотрят в сторону молодых и перспективных языков. LISP был изобретен почти 60 лет назад, он дал начало функциональному программированию. Благодаря ему мы знаем о garbage collection, функциях высшего порядка, рекурсии и многом другом. В наше время LISP вернулся в виде языка Clojure и его диалекта ClojureScript. Из этого доклада вы узнаете о том, что такое ClojureScript и что ему есть предложить современному разработчику веб-интерфейсов.
2013년 11월, HTML5 융합기술 포럼 창립 기념 세미나 발표자료
전자출판표준인 EPUB3는 HTML5, CSS3, Java Script를 근간으로 한 일종의 프로파일링 표준이다. 왜 EPUB3를 개발하게 되었는지에 대한 배경과 HTML5의 킬러 애플리케이션으로서 전자출판 분야에 대한 역할과 기대를 설명한 자료이다.
Having a fast, low-friction Edit/Build/Test cycle is one of the best and easiest ways to increase developer productivity across an organization.
This breadth-first tour covers some of the tools we use at Basho to speed up and streamline the Edit/Build/Test cycle for our Erlang projects.
These are the outline slides that I used for the Pune Clojure Course.
The slides may not be much useful standalone, but I have uploaded them for reference.
Concurrent programming is one of the major challenges for the software industry. We are in a time of massive experimentation as language designers and programmers search for ways to make concurrent programming easier, less error prone, and more reliable.
This talk will be a survey of concurrent programming constructs which are currently available in some programming language or library. We will look at programming model being presented, as well as examining some of the implementation challenges for the various models.
Jenny Pawlak, Brian Gracin and myself performed an optional presentation on the language Clojure for our Programming Languages class. This is meant to be an introduction to the language to those who already know about functional languages, particularly Haskell.
Clojure is a new dialect of LISP that runs on the Java Virtual Machine (JVM). As a functional language, it offers great benefits in terms of programmer productivity; as a language that runs on the JVM, it also offers the opportunity to reuse existing Java libraries. Simon’s interest is in using Clojure to build desktop applications with the Java Swing GUI library. In this presentation Simon discusses how the power of Clojure can be applied to Swing, and whether it hits the sweet spot.
A presentation to introduce the Lobos project made at the Bonjure group meeing on 2011/01/21. For more information on Lobos, visit the website: http://budu.github.com/lobos/
Presentation given at the 2013 Clojure Conj on core.matrix, a library that brings muli-dimensional array and matrix programming capabilities to Clojure
Finally Java SE 7 is GA and you can start using it. This talk will cover the most important new features of the language and the virtual machine. It will also cover some features that did not make it in to the SE 7 release. Finally we will discuss current state of Java as an ecosystem and my analysis and hopes for the future.
Confessions of a developer community builderJohn Stevenson
Slides from my talk on building developer communities at London Software Craftsmanship conference 5th & 6th October.
I share my experiences of interacting with the software development community over the last 22 years.
Discussion includes what kinds of events you could run in your community and how to get your community started.
Progscon 2017: Taming the wild fronteer - Adventures in ClojurescriptJohn Stevenson
Progscon 2017 conference talk, introducing Clojurescript for a functional programming approach to building React.js apps.
Examples include using React.js directly and the Om Clojurescript library that closely follows the React.js API. Also cover a simpler approach to React with the Clojurescript libraries called Reagent and Rum.
Discussing the challenges of communication that affect us all and techniques to help you be more effective
- Six Thinking Hats
- Thinking Fast & Slow
- Cognitive bias / confirmation bias
This talk was last given at DevRelCon in London, December 2016.
Get into Functional Programming with ClojureJohn Stevenson
A brief guide on how to think in the way of Functional Programming, using Clojure as the example code.
Covers the main concepts and abstractions within Functional Programming & Clojure
Presented at several conferences and meetup events through 2016, with a video captured via GoPro at CeBIT Developer world 2016 on youtube at:
https://www.youtube.com/watch?v=mEfqULqChZs
Helping others learn Clojure can be a little different to how you learnt. What makes sense for one person may not make relate to another persons experiences. This presentation gives a brief introduction to guiding people into Clojure.
This presentation was first given at Clojure Remote 2016
Git and github - Verson Control for the Modern DeveloperJohn Stevenson
An introduction to Git and Github, tools for distributed version control that give an easy to use and highly collaborative approach to version code and configuration.
An overview of Functional Programming and Clojure, helping you understand the importance of minimising side effects and walking through examples of functional programming concepts.
Dreamforce14 Metadata Management with Git Version ControlJohn Stevenson
An introduction to using Git version control to manage changes in the metadata of your Salesforce Org as you develop your apps.
Your app is put into an unmanaged package, copied to your local machine with Force.com CLI and changes pushed to Github using Github for Mac/Windows client.
An introduction to Heroku, the Platform as a Service from Salesforce for all your customer facing applications.
Discover how to get going with the Heroku platform and additional services you can use to speed up the deployment of your custom application.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
Generating a custom Ruby SDK for your web service or Rails API using Smithyg2nightmarescribd
Have you ever wanted a Ruby client API to communicate with your web service? Smithy is a protocol-agnostic language for defining services and SDKs. Smithy Ruby is an implementation of Smithy that generates a Ruby SDK using a Smithy model. In this talk, we will explore Smithy and Smithy Ruby to learn how to generate custom feature-rich SDKs that can communicate with any web service, such as a Rails JSON API.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
2. Its a strange kind of love...
Clojure is very different
Part of your brain may rebel !!
Homo-Iconic
List based
Immutable state
Dynamically typed
Tiny syntax
Infinitely extensible
with Macros
3. What is Clojure
Functional programming on the JVM
A better Lisp ?
4. Why get functional ?
Clock speeds stopped getting faster around
2005
Cant get around the speed of silicon switches
Moores law still in effect
More cores added every 18 months
Laptops with 128 cores by 2020 ??
Concurrency at the hardware level
Not just multi-threading
6. Why a better Lisp ?
Clojure is easier to understand
Nicer libraries
Great interoperability with Java
platform
Closer to pure functional
language
Explicitly define mutable state
STM – transactional memory
8. Why create Clojure
Concurrency in Java / OO is challenging
Mutable state-full paradigm
Fast enough persistent data structures made it
viable
Functions as first class
Functions part of data structure
Functions do not have “side effects”
Focus on computation (maths) rather than
procedural algorithms
9. Why use Clojure
Its a pure functional programming language
You can use existing Java code and platform
Simple syntax
It gets you thinking differently !!!
An excuse to learn Emacs properly ??
18. We're not in Kansas any
more...
Java
package … ;
class …;
member variables;
access retType methodName (param, param) {…}
Clojure
(ns name-space-name)
(defstruct my-data-struture :label-name)
(functionName param (fn param))
; param's can be functions too !!
20. … a tree structure
Functions are data
Data structures are functions !!
21. Download
clojure.org
Or via buld tool
Maven
Leiningen
Cake
Java
At least version 5
Version 6 better
performance and
reporting
22. All hail the REPL
An interactive shell for clojure
Using Leiningen (Line – ing – en)
https://github.com/technomancy/leiningen/
lein
lein repl
23. Leiningen Clojure project
lein new
lein deps
lein repl
lein swank
Create a new clojure project
Download clojure
Start the interactive shell
Start repl server for emacs
24. Leiningen project file
(defproject my-jax-london-project "1.0.0-SNAPSHOT"
:description "A meaningful description"
:dependencies [[org.clojure/clojure "1.2.1"]
[org.clojure/clojure-contrib "1.2.0"]]
:dev-dependencies [[swank-clojure "1.2.1"]
[org.clojars.rayne/autodoc "0.8.0-
SNAPSHOT"]]
:autodoc { :name "London Clojure dojo", :page-title "Dojo API"}
;; Only re-fetch deps when they change in project.clj or when :library-path directory is empty.
:checksum-deps true
:license {:name "Eclipse Public License - v 1.0"
25. Loading code into the REPL
(load-file "temp.clj")
Stuff too big to type
use an absolute path or a path relative to
where you launched the REPL
Use Emacs or other IDE when you're ready
39. Overloading functions
(defn make
([ ] ; the make function that takes no arguments
(struct vector 0 0))
([x y] ; ... takes x and y keywords as arguments
(struct vector x y))
)
40. Pure functions – no side effects
Clojure functions are pure
they have no side effects
Unless you define them as such
Pure functions are easy to develop, test, and
understand
Aim for pure functions where possible
41. Clojure data structures
( Lists ) - Ordered collection of elements
(list 1 3 5) '(8 13 21)
{ map }
[ Vectors ] - Optimised for random access
[:tom :dick :harry]
Lists are for code, Vectors for data
(nth [:tom :dick :jane :harry ] 2)
42. List operations
(first 1 2 3)
The head of the list
(last 7 8 9)
The last element of the list
(rest 1 2 3 4 5)
Everything but the head
(cons :new-list '(1 2 3 4 5))
New list, given head and tail
43. More data structures...
(defstruct date :day :month :year)
(struct date)
as we did not specify any parameters, we just
get nil values
things in curly brackets are hash maps - the
usual Java hashmaps
44. maps
{ :a 1 :b 2}
user=> { :a 1 :b 2}
{:a 1, :b 2}
user=> { :a 1 :b }
java.lang.ArrayIndexOutOfB
oundsException: 3
user=> { :a 1 :b 2}
{:a 1, :b 2}
user=> { :a 1 :b 3} ; this
should make the repl
complain in clojure 1.2,
fine in 1.1
{:a 1, :b 3}
user=> {:a {:a 1}}
{:a {:a 1}}
user=> {{:a 1} :a}
{{:a 1} :a}
; idiom - put :a on the left
46. Your own data structures
Special forms
(def johnny {:first-name "John", :last-name
"Stevenson"})
(defstruct person :first-name :last-name)
(defrecord person [String :first-name String
:last-name] :allow-nulls false)
47. Memory use
Once all references to an immutable structure
disappears it can be garbage collected.
Loops that create intermittent structures are
garbage collected every turn of the loop.
;;Memory : 0
(let [a (range 50000)]) ;; Memory: "big" while
the let is "executing"
;;Memory : 0 -- no reference to a anymore !
48. macros
Define extensions to the language
Clojure only has 7 primitive functions
Everything else in the language is created with
macros
Allows the language to be extended easily
without changes to the compiler
49. Special forms
Recognized by the Clojure compiler and not
implemented in Clojure source code.
A relatively small number of special forms
New ones cannot be implemented
catch, def, do, dot ('.'), finally, fn, if, let, loop,
monitor-enter, monitor-exit, new, quote,
recur, set!, throw, try and var
50. if
user=> (doc if)
-------------------------
if
Special Form
Please see http://clojure.org/special_forms#if
nil
51. Sequences
Sequences are logical views of collections
Logical lists
Java collections, Clojure-specific collections,
strings, streams, directory structures and XML
trees.
New Clojure collections created efficiently
Creates a sort of branch (delta) in the data
structure tree
53. Software Transactional
Memory
Works like transactional databases
Provides safe, concurrent access to memory
Agents allow encapsulated access to mutable
resources
54. Sharing mutable data
Use mutable references to immutable data
Reference Types
synchronous access to multiple pieces of
shared data ("coordinated") by using STM
Atoms
synchronous access to a single piece of shared
data.
Agents
asynchronous access to a single piece of
shared data
55. Name-spaces
Define a namespace
(ns name-space-name)
Include namespace code
(use 'names-space-name)
Like a package statement in Java
56. Clojure Libraries
(use 'clojure.contrib.str-utils)
'
Dont treat the next thing as a function
Open source libraries - http://clojars.org/
57. Recursive functions
Functions that call
themselves
Fractal coding
Tail recursion
Avoids blowing the
heap
A trick as the JVM
does not support
tail recursion
directly :-(
58. Tail recursion
(defn factorial [x]
(if (= x 0)
1
(* x (factorial (- x 1))
)))
Dont blow your stack
!!
59. TDD with Clojure is nice
Clojure test
(deftest test-name
(is (= value (function params))) )
61. Working with Java
Java Classes
fullstop after class name
(JFrame. )
(Math/cos 3) ; static method call
Java methods
fullstop before method name
(.getContentPane frame) ;;method name first
(. frame getContentPane) ;;object first
63. Working with Java (2)
Clojure gives you clean, simple, direct access
to Java
call any Java API directly
(System/getProperties)
-> {java.runtime.name=Java(TM) SE Runtime
Environment
64. Calling Clojure from Java
Export the clojure to a .jar
Add the jar to the classpath
Import the library in your code
Call it like any other method
65. Errors are inevitable
In the REPL
(printStackTrace *e)
*e holds the last exception raised
Clojure exceptions are Java exceptions
66. Managing State in Immutable
world
Mutable data structures to share between
threads (Software Transactional Memory)
refs, vars, atoms, agents
No locks required for thread safe code, no
deadlocks or race conditions
Atomically apply changes
67. Mutable functions
Swap!
Name functions that have side effects with an
exclamation mark
Naming convention
69. Documentation
(doc function-name)
(javadoc class-name)
(defn function-name
“A meaningful
description of the
function”
params )
Show fn description
Show javadoc in
browser
Write documentation
for your own
functions
70. Example documentation
(doc str)
Use doc to print the documentation for str:
user=> (doc str)
-------------------------
clojure.core/str
([] [x] [x & ys])
With no args, returns the empty string. With one
arg x, returns x.toString(). (str nil) returns
the empty string. With more than one arg,
returns the concatenation of the str values
of the args.
Fully qualified
namespace
Arguments
Details
71. find-doc
(find-doc “reduce”)
user=> (find-doc "reduce" )
-------------------------
clojure/areduce
([a idx ret init expr])
Macro
... details ...
-------------------------
clojure/reduce
([f coll] [f val coll])
... details ...
Search for functions
you dont know
Keyword parameter
72. Autodoc
Generate a website for your API's
http://tomfaulhaber.github.com/auto
doc/
Add dependency to your build file
http://clojars.org/org.clojars.rayne/autodoc
lein deps
lein autodoc
73. Where next
Coding dojo – London / start your own
www.londonjavacommunity.co.uk
Books – Programming Clojure (Pragmatic)
Website – clojure.org dev.clojure.org
Full Disclojure
vimeo.com/channels/fulldisclojure
clojure.jr0cket.co.uk
99 problems in clojure
Clojure has a programmatic macro system which allows the compiler to be extended by user code
You can add your own language features with macros. Clojure itself is built out of macros such as defstruct:
(defstruct person :first-name :last-name)
If you need different semantics, write your own macro. If you want a variant of structs with strong typing and configurable null-checking for all fields, you can create your own defrecord macro, to be used like this:
(defrecord
person [String :first-name String :last-name]
:allow-nulls false)
This ability to reprogram the language from within the language is the unique advantage of Lisp. You will see facets of this idea described in various ways:
Lisp is homoiconic - Lisp code is just Lisp data. This makes it easy for programs to write other programs.
The whole language is there, all the time. Paul Graham’s essay “Revenge of the Nerds” explains why this is so powerful. http://www.paulgraham.com/icad.html
Lisp syntax also eliminates rules for operator precedence and associativity, with fully parenthesized expressions, there is no possible ambiguity
Hickey's primary interest was concurrency — he wanted the ability to write multi-threaded applications, but increasingly found the mutable, stateful paradigm of object oriented programming to be part of the problem
The idea of a functional Lisp integrated with a commercially accepted host platform just seemed like chocolate and peanut butter. Coming up with persistent data structures that were fast enough was the tipping point for my considering it viable.
functions as first-class objects, meaning that functions can be placed into data structures, passed as arguments to other functions, evaluated in comparisons, even returned as the return value of another function. Moreover, functions do not have "side effects" — the ability to modify program state or data. This paradigm focuses on computation in the mathematical sense, rather than procedural algorithms, and is a completely different approach to programming.
Clojure does provide persistent data structures For application developers, the most significant distinction is that Clojure defaults to making all data structures immutable
developers must use one of four special mutable structures that are explicitly designed to be shared between threads: refs, vars, atoms, and agents. Clojure uses software transactional memory (STM) to coordinate changing these mutable structures while keeping them in a consistent state, much like a transactional database. This model makes it considerably simpler to write thread-safe code than it is in object oriented languages. No locks are required, therefore there are no deadlocks or race conditions.
Throw away your knowledge about OO and try something different
The downside of Lisp’s simple, regular syntax, at least for beginners, is Lisp’s fixation on parentheses and on lists as the core data type. Clojure offers an interesting combination of features that makes Lisp more approachable for non-Lispers.
The downside of Lisp’s simple, regular syntax, at least for beginners, is Lisp’s fixation on parentheses and on lists as the core data type. Clojure offers an interesting combination of features that makes Lisp more approachable for non-Lispers.
The downside of Lisp’s simple, regular syntax, at least for beginners, is Lisp’s fixation on parentheses and on lists as the core data type. Clojure offers an interesting combination of features that makes Lisp more approachable for non-Lispers.
The downside of Lisp’s simple, regular syntax, at least for beginners, is Lisp’s fixation on parentheses and on lists as the core data type. Clojure offers an interesting combination of features that makes Lisp more approachable for non-Lispers.
The downside of Lisp’s simple, regular syntax, at least for beginners, is Lisp’s fixation on parentheses and on lists as the core data type. Clojure offers an interesting combination of features that makes Lisp more approachable for non-Lispers.
Note: prefix notation
What are the 7 primitive functions?
When you require a library named clojure.contrib.str-utils, Clojure looks for
a file named clojure/contrib/str-utils.clj on the CLASSPATH
To avoid having to use the namespace for your library, you have to use refer, like so - (refer 'examples/introduction)
The use function does both require refer, like so –
(use 'examples.introduction)
o force a library to reload:
(use :reload-all 'examples.introduction)
The :reload-all flag is useful if you are making changes and want to see results without restarting the REPL.
This is barfing because the evaluator has to keep around state for each call due to the expression (* x (factorial (- x 1))) . We need to make this function tail recursive.
recur can be thought of as the Clojure operator for looping. Think of it like a function call for the nearest enclosing let or function definition supplied with new variables. Naively we can switch over to using this by doing:
user> (defn factorial2 [x]
(if (= x 0)
1
(* x (recur (- x 1)))))
But this is a compile-time error (which in itself is pretty neat!).
java.lang.UnsupportedOperationException: Can only recur from tail position (NO_SOURCE_FILE:4)
An accumulator parameter is an extra parameter to a function that's used to gather intermediate parts of the calculation. If we do this, we can make sure that the recur call is in the tail position. Using an anonymous function we get:
(defn factorial3 [x]
((fn [x y]
(if (= x 0)
y
(recur (- x 1) (* x y)))) x 1))
Now when recur is used, it doesn't need to keep any of the previous stack frame around. This means we can finally calculate factorial 1000000, which begins with 282 and ends with lots of zeros!
Use doc to print the documentation for str:
user=> (doc str)
-------------------------
clojure.core/str
([] [x] [x & ys])
With no args, returns the empty string. With one arg x, returns
x.toString().
(str nil) returns the empty string.
With more than one arg, returns the concatenation of the str values of the args.
The first line of doc’s output contains the fully qualified name of the
function.
The next line contains the possible argument lists, generated directly from the code. (Some common argument names and their uses are explained in the sidebar on the following page.)
Finally, the remaining lines contain the function’s doc-string, if the function definition included one.