The Curious Clojureist

Similar documents
Stuart

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

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

Clojure Lisp for the Real clojure.com

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

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

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.

Clojure Lisp for the Real #clojure

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

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

Persistent Data Structures and Managed References

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.

building DSLs with language workbenches

comparing groovy & jruby *

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

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

Identity, State and Values

What if Type Systems were more like Linters?

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

Functional Programming and the Web

design patterns in ruby

Macro #clojureconj

introduction to jruby

Michiel DomCode, May 26th 2015

Declarative concurrency. March 3, 2014

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

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

Towards Lean 4: Sebastian Ullrich 1, Leonardo de Moura 2.

Ruby: Introduction, Basics

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

CS 314 Principles of Programming Languages

Multi-core Parallelization in Clojure - a Case Study

Drinking from the Clojure fire hose

Reference types in Clojure. April 2, 2014

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

A Small Interpreted Language

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

Functional programming is a productive

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

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

Tackling Concurrency With STM

building dsl s in static & dynamic languages

CS 11 Haskell track: lecture 1

Scala, Your Next Programming Language

Stop coding Pascal. Saturday, April 6, 13

COP4020 Programming Assignment 1 - Spring 2011

Functional Programming

Rails in the Large: Building the Biggest (Enterprise) Rails Application in the World

Introduction to Clojure Concurrency (and data structures)

Clojure: Enemy of the State

Concepts of programming languages

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

Scala : an LLVM-targeted Scala compiler

Design Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8

Functional Programming. Pure Functional Programming

Clojure for OOP folks Stefan innoq

Functional Programming. Pure Functional Languages

Executable Formal Specifications with Clojure. Matti Nieminen

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Haskell Programming

Metaprogramming. Concepts of Programming Languages. Alexander Schramm. 2. November Institut für Softwaretechnik und Programmiersprachen

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

Functional Languages. Hwansoo Han

Racket: Macros. Advanced Functional Programming. Jean-Noël Monette. November 2013

Ruby: Introduction, Basics

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

CPS506 - Comparative Programming Languages Elixir

Intro. Scheme Basics. scm> 5 5. scm>

Normal Order (Lazy) Evaluation SICP. Applicative Order vs. Normal (Lazy) Order. Applicative vs. Normal? How can we implement lazy evaluation?

Lecture 8: Summary of Haskell course + Type Level Programming

Introducing Wybe a language for everyone

First Programming Language in CS Education The Arguments for Scala

G Programming Languages - Fall 2012

Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7

CSCI-GA Scripting Languages

Extending Jython. with SIM, SPARQL and SQL

Reasoning About Programs Panagiotis Manolios

JVM ByteCode Interpreter

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

SCHEME AND CALCULATOR 5b

CS 314 Principles of Programming Languages

Clojure Distilled. Immutable

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

Programming Clojure, Third Edition

Chapter 13: Reference. Why reference Typing Evaluation Store Typings Safety Notes

Functional Programming. Pure Functional Languages

Common LISP-Introduction

Imperative languages

COMP 202 Java in one week

Notes on Higher Order Programming in Scheme. by Alexander Stepanov

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

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

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

From the λ-calculus to Functional Programming Drew McDermott Posted

Scheme Tutorial. Introduction. The Structure of Scheme Programs. Syntax

PERSISTENT SEQUENCES WITH EFFECTIVE RANDOM ACCESS AND SUPPORT FOR INFINITY

Programming Clojure. Extracted from: Second Edition. The Pragmatic Bookshelf

CS558 Programming Languages

CS 360 Programming Languages Interpreters

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

Transcription:

The Curious Clojureist NEAL FORD director / software architect meme wrangler ThoughtWorks nford@thoughtworks.com 2002 Summit Boulevard, Atlanta, GA 30319 nealford.com thoughtworks.com memeagora.blogspot.com @neal4d

what is this talk about? clojure s 4 elevators: 1. java interop 2. lisp 3. functional 4. state & concurrency the ecosystem the coolness

what is clojure? Clojure is a dynamic, strongly typed, functional, highperformance implementation of a lisp on the JVM.

isn t lisp the one with all the () s? yes

why all the () s? Lisp is a homoiconic language. Lisp programs consist of lisp data structures. all kinds of useful!

ecosystem

clojure.org/

code.google.com/p/counterclockwise/

github.com/technomancy/emacs-starter-kit

github.com/technomancy/leiningen

compojure (web framework) clj-record (pseudo-port of ActiveRecord) github.com/weavejester/ compojure github.com/duelinmarkers/ clj-record clojureql (relational algebra -> SQL) clojurescript (clojure on JavaScript) github.com/laujensen/ clojureql github.com/clojure/ clojurescript

what does clojure code look like?

data types? type example java equivalent string "foo" String character \f Character regex #"fo*" Pattern a. p. integer 42 Int/Long/BigInteger double 3.14159 Double a.p. double 3.14159M BigDecimal boolean true Boolean nil nil null symbol foo, + N/A keyword :foo, ::foo N/A

data literals? type properties example list vector map singly-linked, insert at front (1 2 3) indexed, insert at rear [1 2 3] key/value {:a 100 :b 90} set key #{:a :b}

function calls? semantics: fn call arg (println "Hello World") structure: symbol list string

function definition? define a fn fn name docstring arguments (defn greet "Returns a friendly greeting" [your-name] (str "Hello, " your-name)) fn body

homoiconicity? symbol symbol string vector (defn greet "Returns a friendly greeting" [your-name] (str "Hello, " your-name)) it s all data list

function meta-data? prefix with ^ class name or arbitrary map (defn ^String greet "Returns a friendly greeting" [your-name] (str "Hello, " your-name))

what is the java interop story with clojure?

interop? syntax extensions to reach all of Java compiles to bytecode fast call Clojure from Java

construction? new Widget("foo") (Widget. "red")

static members? Math.PI Math/PI

instance members? rnd.nextint() (.nextint rnd)

chained access? person.getaddress().getzipcode() (.. person getaddress getzipcode)

() count? 8 6

how would you implement an interface? interface (reify Runnable (run [] (println "Hello"))) method bodies add more interfaces here

what would a typical method look like in clojure? isblank()

isblank()

isblank() types

isblank() class

isblank() + higher-order function

isblank() corner cases

isblank() lispify!

when does verbosity == obscurity?

what s so special about lisp? feature industry norm cool kids clojure conditionals variables garbage collection recursion function type symbol type whole language available everything s an expression homoiconicity http://www.paulgraham.com/diff.html

what are special forms? the syntactic scaffolding of your language imports scopes protection meta-data control flow anything using a keyword

how are special forms outside lisp different? μ limited to specific use μ look different μ may have special semantics unavailable to you μ hamper reuse

what s special about lisp s special forms? λ look just like everything else λ may have special semantics available to you λ can be augmented with macros

all forms are created equal? form syntax example function list (println "hello") operator list (+ 1 2) method call list (.trim " hello ") import list (require 'mylib) metadata list (with-meta obj m) control flow list (when valid? (proceed)) scope list (dosync (alter...))

why is this important? special forms are easier to understand individually but create combinatorial complexity in aggregate to deal with complexity, you categorize & you end up

what s the alternative to patterns in lisp? m a c r o s

how can macros reduce repetition? (.add frame panel) (.pack frame) (.setvisible frame true) (doto frame (.add panel) (.pack) (.setvisible true) say it only once doto returns frame now we have an expression

Many of the features of Clojure are implemented with macros. How can you tell? you can t!

an example of a simple macro? (defmacro when [test & body] (list 'if test (cons 'do body))) (when x (println "x is true"))) macroexpansion it s all data (if x (do (println "x is true")))

what are some types of macros? type control flow vars java interop examples when when-not and or defn defmacro defmulti.. doto deftype proxy rearranging -> ->> -?> scopes special form dosync time with-open fn lazy-seq let

how does functional make my life better?

how does function change the structure of my code? indexofany

indexofany StringUtils.indexOfAny(null, *) = -1 StringUtils.indexOfAny("", *) = -1 StringUtils.indexOfAny(*, null) = -1 StringUtils.indexOfAny(*, []) = -1 StringUtils.indexOfAny("zzabyycdxx",['z','a']) = 0 StringUtils.indexOfAny("zzabyycdxx",['b','y']) = 3 StringUtils.indexOfAny("aba", ['z']) = -1

indexofany

indexofany simplify corner cases

indexofany type decls

indexofany + when clause

indexofany + comprehension

indexofany lispify

which version is simpler? imperative functional functions 1 1 classes 1 0 internal exit points 2 0 variables 3 0 branches 4 0 boolean ops 1 0 function calls* 6 3 total 18 4

which is more general? ; idxs of heads in stream of coin flips (index-filter #{:h} [:t :t :h :t :h :t :t :t :h :h]) -> (2 4 8 9) ; Fibonaccis pass 1000 at n=17 (first (index-filter #(> % 1000) (fibo))) -> 17

which is more general? imperative functional searches strings searches any sequence matches characters matches any predicate returns first match returns lazy seq of all matches

what s clojure s unique take on state & concurrency?

what about persistent data structures? immutable change by function application maintain performance guarantees full fidelity old versions

how would that work with a linked list? your list my list newt tern rabbit

and more complex data structures? your trie bit-partitioned tries my trie log2 n: too slow

how many tries to make it fast enough? 32-way tries.......................................... log32 n: fast enough!

what s wrong with variables?!?? variable??? identity state variable??? time

what s clojure s view of identity identity explicit semantic value value identity value state

compare identity, state, & time? term value identity state time meaning immutable data in a persistent data structure series of causally related values over time identity at a point in time relative: before/ simultaneous/after ordering of causal values

what is clojure s epochal time model? F F F Process events (pure functions) v1 v2 v3 v4 Observers/ Identity (succession of states) perception/ memory States (immutable values)

what s the unified update model? return becomes next state of ref (change-state ref fn [args*]) snapshot always available no user locking, no deadlocks writes never impede readers gets current state of ref

software transactional memory

how does STM work? v1 v2 v3 v4 v1 v2 v3 v4 v1 v2 v3 v4 v1 v2 v3 v4 F F F F transactions F F F F F F F F

what s the syntax for STM? identity (def messages (ref [])) initial value

how do you read a value? (deref messages) => [] @messages => []

how do you alter a message? (alter r update-fn & args) oldval r (apply update-fn oldval args) newval

how do you update a message? apply an... (defn add-message [msg] (dosync (alter messages conj msg))) scope a transaction...update fn

what s cool about clojure? highly expressive language seamless java interop functional advanced concurrency

? s please fill out the session evaluations NEAL FORD director / software architect meme wrangler ThoughtWorks This work is licensed under the Creative Commons Attribution-Share Alike 3.0 License. http://creativecommons.org/licenses/by-sa/3.0/us/ nford@thoughtworks.com 2002 Summit Boulevard, Atlanta, GA 30319 nealford.com thoughtworks.com memeagora.blogspot.com @neal4d