Clojure is. A dynamic, LISP-based. programming language. running on the JVM

Similar documents
Symbols. abstractions, implementing, 270 through indirection, 77 with macros, 183 abstract syntax tree (AST), 149

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

Seminar on Languages for Scientific Computing Aachen, 6 Feb Navid Abbaszadeh.

.consulting.solutions.partnership. Clojure by Example. A practical introduction to Clojure on the JVM

Clojure Lisp for the Real clojure.com

The Curious Clojureist

Introduction Basics Concurrency Conclusion. Clojure. Marcel Klinzing. December 13, M. Klinzing Clojure 1/18

Clojure. A (not-so-pure) functional approach to concurrency. Paolo Baldan Linguaggi per il Global Computing AA 2016/2017

Clojure Lisp for the Real #clojure

Stuart

This tutorial is designed for all those software professionals who are keen on learning the basics of Clojure and how to put it into practice.

Clojure. A Dynamic Programming Language for the JVM. Rich Hickey

Clojure Concurrency Constructs. CSCI 5828: Foundations of Software Engineering Lecture 12 10/02/2014

ClojureScript. as a compilation target to JS. Michiel Vijay FP AMS October 16th 2014

Clojure: Enemy of the State

Lazytest Better Living Through Protocols. Stuart Sierra. Clojure NYC April 15, 2010

Clojure for OOP folks Stefan innoq

Reagent. a ClojureScript interface to React. React Amsterdam Meetup 12 Feb. 2015

Clojure. A Dynamic Programming Language for the JVM. (and CLR) Rich Hickey

Michiel DomCode, May 26th 2015

Declarative concurrency. March 3, 2014

Clojure. The Revenge of Data. by Vjeran Marcinko Kapsch CarrierCom

Macro #clojureconj

Persistent Data Structures and Managed References

Identity, State and Values

Programming Clojure, Third Edition

Clojure Distilled. Immutable

INF4820: Algorithms for Artificial Intelligence and Natural Language Processing. Common Lisp Fundamentals

POETRY OF PROGRAMMING CODE READING EXERCISES IN CLOJURE V

June 27, 2014 EuroClojure 2014 Krakow, Poland. Components. Just Enough

Multi-core Parallelization in Clojure - a Case Study

Functional Programming and the Web

Executable Formal Specifications with Clojure. Matti Nieminen

Week 2: The Clojure Language. Background Basic structure A few of the most useful facilities. A modernized Lisp. An insider's opinion

Data Structures in Functional Languages

Use of Clojure in Undergraduate CS Curriculum

Functional Programming Lecture 1: Introduction

Common LISP Tutorial 1 (Basic)

Behind the scenes - Continuous log analytics

Reference types in Clojure. April 2, 2014

Macros, and protocols, and metaprogramming - Oh My!

COP4020 Programming Assignment 1 - Spring 2011

Functional Programming. Big Picture. Design of Programming Languages

Quote of the Day. CS Functional Programming. Introductory Notes on Lisp/Clojure. Another Quote. What is Clojure? 1-4

What if Type Systems were more like Linters?

Functional programming is a productive

Ruby: Introduction, Basics

Drinking from the Clojure fire hose

Java.net Package and Classes(Url, UrlConnection, HttpUrlConnection)

Clojure & Incanter for Java Programmers

Stop coding Pascal. Saturday, April 6, 13

A Small Interpreted Language

Ruby: Introduction, Basics

Functional Languages. CSE 307 Principles of Programming Languages Stony Brook University

Your First Ruby Script

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 2. ÚVOD DO LISPU: ATOMY, SEZNAMY, FUNKCE,

Clojure philosophy. This chapter covers. The Clojure way Why a(nother) Lisp? Functional programming Why Clojure isn t especially object-oriented

COPYRIGHTED MATERIAL INDEX. Symbols and Numerals. # in URL, 146

SAMPLE CHAPTER IN ACTION SECOND EDITION. Amit Rathore Francis Avila MANNING

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Functional Programming

Symbolic Computation and Common Lisp

From Lisp to Clojure/Incanter and R An Introduction. Shane M. Conway January 7, 2010

1.3.4 case and case* macro since 1.2. Listing Conditional Branching, Fast Switch. Listing Contract

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Basics

Why Prismatic Goes Faster With Clojure

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

Chapter 1. Fundamentals of Higher Order Programming

4/19/2018. Chapter 11 :: Functional Languages

Chapter 11 :: Functional Languages

Lecture 13: Expression Evaluation

Racket. CSE341: Programming Languages Lecture 14 Introduction to Racket. Getting started. Racket vs. Scheme. Example.

11/6/17. Functional programming. FP Foundations, Scheme (2) LISP Data Types. LISP Data Types. LISP Data Types. Scheme. LISP: John McCarthy 1958 MIT

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

BUILDING DECLARATIVE GUIS WITH CLOJURE, JAVAFX AND FN-FX DR. NILS BLUM-OESTE

FP Foundations, Scheme

Functional Programming Patterns And Their Role Instructions

Tackling Concurrency With STM. Mark Volkmann 10/22/09

Tackling Concurrency With STM

Scala : an LLVM-targeted Scala compiler

Introduction to lambda calculus Part 3

Functional programming in LISP

CSCE 314 Programming Languages

Modern Programming Languages. Lecture LISP Programming Language An Introduction

Chapter 15. Functional Programming Languages

python. a presentation to the Rice University CS Club November 30, 2006 Daniel Sandler

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples

A brief tour of history

Functional Programming. Pure Functional Languages

Ruby: Introduction, Basics

John McCarthy IBM 704

Functional Programming

A Practical Optional Type System for Clojure. Ambrose Bonnaire-Sergeant

Functional Programming Lecture 13: FP in the Real World

Java, with a Clojure

Notes from a Short Introductory Lecture on Scala (Based on Programming in Scala, 2nd Ed.)

A Folding Language. Ola Bini computational metalinguist fredag, 2009 september 18

clojure & cfml sitting in a tree sean corfield world singles

CS 314 Principles of Programming Languages

Transcription:

(first '(Clojure.))

Clojure is A dynamic, LISP-based programming language running on the JVM

Origin 2007, Rich Hickey.. 1958, John McCarthy

Features Functional Homoiconic Immutability (persistent data structures) Powerful (composition, macros)

Plus Concurrency (separates identity and state) Pragmatic (compact syntax, high-level collections) Java Interop (symbiotic)

Applicability Designed as a general purpose language where functional style is idiomatic.. Use anywhere Java (the JVM) is used

The JVM?

Fun!

Homoiconic (+ 1 1) Prefix notation List Processing (LISP) Code is Data Math Substitution Principle => Predictable!

Scalars Collections Special Forms Syntax

Scalars \c ; characters "Hello" ; strings 42 ; numbers 3/2 ; ratios true ; booleans nil

Names ; symbols i println + empty? next-state.touppercase ; keywords :name :use

Collections

Lists (println "Hello") ;=> Hello '(println "Hello") ;=> (println "Hello") (first '(println "Hello")) ;=> println

Vectors ["bag" "of" 4 "chips"]

Hash-maps {:name "Intro" :date "2012-05-29"}

Sets #{"unique" "snowflakes"}

Commas ; commas: just whitespace! ["bag", "of", 4, "chips"] {:name "Intro", :date "2012-05-29"}

Special Forms

(def i 1) Define

(if true (/ 1 1) (/ 1 0)) If

Functions (fn [name] (str "Hello " name "!"))

Named Functions (def greet (fn [name] (str "Hello " name)))

The defn macro (defn greet [name] (str "Hello " name))

Let the local names in (defn greet [name] (let [greeting "Hello" out (str greeting " " name)] out))

Sugared Lambdas #(str %1 %2) ; same as (fn [a1 a2] (str a1 a2))

Some More Sugar #"\w+" ; regexps @ref ; (deref ref)

The rest is just eval/apply

Basic Usage => represents results

Vectors (def items [1 2 3]) (first items) => 1 (rest items) => (2 3) (items 0) => 1

Adding to collections (cons items [3 4]) => [1 2 3 4] (conj items 3) => [1 2 3]

Mapping (map inc [1 2 3]) => (2 3 4) (map #(+ % 1) [1 2 3]) => (2 3 4)

Reducing (reduce #(- %1 %2) [1 2 3]) => -4

For Comprehension (for [i (range 1 7) :when (even? i)] (str "item-" i))) => ("item-2" "item-4" "item-6")

Laziness (take 3 (repeat 1)) => (1 1 1) (take 3 (filter even? (iterate inc 1))) => (2 4 6) (read-lines "/var/huge-data.log")

Composing Data

Constructs (def persons [{:id 1 :name "Some Body"} {:id 2 :name "Some Other"}]) (let [person (persons 0)] (person :name)) => "Some Body"

The key is getting the value (:name (first persons)) => "Some Body" (map :name persons) => ("Some Body" "Some Other")

Records (defrecord Person [id name]) (let [person (Person. 1 "Some Body")] (:name person)) => "Some Body"

Destructuring (let [[one other] [1 2]] (+ one other)) => 3

The Relevant Parts (let [person {:id 1 :name "Anyone"} {id :id name :name} person] [id name]) => [1 "Anyone"]

Immutability (let [unknown {}] (assoc unknown :name "Neo") (:name unknown)) => nil

One State at a Time (defn reborn [person name] (assoc person :name name)) (println (:name (reborn {} "Neo"))) => "Neo"

Namespaces (ns some.cli (:require [some.core :as core])) (defn -main [& args] (doseq [item args] (println (core/process item))))

Compose Data, Compose Functions Data first Collections Flow Abstractions

How To Think In Clojure

.. leave imperative programming pulling levers flipping switches adding and removing in place

Functional programming Composes data Composes functions Transforms data A succession of states over time

Concurrency

States over Time Value as State Reference to Identity Identity over Time

Time Isolation STM

Atoms (def item-counter (atom 0)) (defn next-item [] (swap! item-counter inc) (str "item-" @item-counter)) (next-item) => "item-1" (next-item) => "item-2"

Refs (def item1 (ref {:a "foo"})) (def item2 (ref {:a "bar"})) (let [v1 (:a @item1) v2 (:a @item2)] (dosync (alter item1 assoc :a v2) (alter item2 assoc :a v1)))

Agents (def info (agent {})) (send info assoc :status :open) ; eventually, ; (assoc info :status :open) ; is called

Java Interop

Monsters In The Cellar Can be shackled by parentheses, even fed immutability, but their nature is wild

.method (.tostring (.resolve (java.net.uri. "http://example.org/a") "/b")) => "http://example.org/b"

Parallel HTTP Fetches (ns parallel-fetch (:import (java.io InputStream InputStreamReader BufferedReader) (java.net URL HttpURLConnection)))

(defn get-url [url] (let [conn (doto (.openconnection (URL. url)) (.setrequestmethod "GET") (.connect))] (with-open [stream (BufferedReader. (InputStreamReader. (.getinputstream conn)))] (.tostring (reduce #(.append %1 %2) (StringBuffer.) (line-seq stream))))))

(defn get-urls [urls] (let [agents (doall (map #(agent %) urls))] (doseq [agent agents] (send-off agent get-url)) (apply await-for 5000 agents) (doall (map #(deref %) agents)))) (prn (get-urls ["http://erlang.org" "http://clojure.org/"]))

Interface On Your Own Terms

Idiom (get-name root) (get-attr link "href") (get-child-elements div)

Protocol (defprotocol DomAccess (get-name [this]) (get-attr [this attr-name]) (get-child-elements [this]))

Realization (extend-type org.w3c.dom.node DomAccess (get-name [this] (.getnodename this)) (get-attr [this attr-name] (if (.hasattribute this attr-name) (.getattribute this attr-name))) (get-child-elements [this] (filter #(= (.getnodetype %1) Node/ELEMENT_NODE) (node-list (.getchildnodes this)))))

Using Clojure For Real

Leiningen $ lein deps $ lein compile $ lein repl $ lein uberjar $ lein ring server-headless

Editors Vim: VimClojure Emacs: Swank IDEA: La Clojure

More Info <http://clojure.org/> <http://clojure.org/cheatsheet> <http://clojuredocs.org/> <http://dev.clojure.org/display/community/clojure+success+stories> <http://www.infoq.com/presentations/are-we-there-yet-rich-hickey> <http://www.infoq.com/presentations/simple-made-easy>

Have Fun!

(thanks!)

@niklasl @valtechsweden

Attribution Clojure Logo Rich Hickey Darth Vader "Where the Wild Things Are" Maurice Sendak * Parallel HTTP Fetches by Will Larson