The joy of clojure

6 downloads 2791 Views 297KB Size Report
A workable definition offunctional programming. 12. The implications offunctional programming 12. 1.4. Why Clojure isn't especially object-oriented 13. Defining ...
The Joy

of Clojure MICHAEL FOGUS CHRIS HOUSER

11 MANNING Greenwich

(74°

w.

long.)

contents foreword xvii preface xix acknowledgments about this book

1

xxi xxiii

I^OtJND.ATnjON'S w****************************************************!

7

-JL

3

Clojure philosophy 1.1

The

Clojure way 4

Simplicity Clarity 6 1.2

Freedom to focus

Consistency

Why a(nother) Lisp? Beauty

1.3

4

9

Functional

5

Empowerment

*

8

Extreme flexibility

programming

9

Code

w

data

1.4

definition offunctional programming implications offunctional programming 12

Why Clojure isn't especially object-oriented Defining terms 13 Imperative "baked in" 15 OOP gives you, Clojure provides »

1.5

Summary

19

ix

77

12

A workable The

5

7

14

12

13 Most

of what

CONTENTS

Drinkingfrom 2.1

the

Scalars

21

Numbers

21

Raiionals

*

*

23

*

24

Vectors

*

24

Vars

25

Sets

25

25

Definingfunctions 26 Simplifying def and defn 27 In-fAacefunctions



*

with

*

28

Locals, loops, and blocks 29

Locals

'

32

29

from

Preventing things

29

33

Unquote Auto-gensym 36

35

operator The..

36 37

SettingJava

*

37*

macro

36

AccessingJava

*

pitch

The doto

and catch

34

Creatingfava

class

instance members with the

instance properties macro

Exceptional circumstances A little

*

36

static class members

instances

32

happening: quoting

Leveragingjava via interop Accessing

30

Loops

-

Quoting



Unquole-splicing

2.9

*

28

Evaluation

2.8

25

Maps

*

28

Blocks

2.7

24

collections

Declaring bindings using def

2.6

*

Making things happen: functions

'with #()

2.5

Floating-point numbers 22 Keywords 23 Strings 23

23

Callingfunctions function definitions 2.4

22

Integers Symbols

Putting things together: Lists

2.3

*

22

Characters

2.2

20

Clojure firehose

38*

.

37

Defining classes

38

38

38

39

Namespaces

Creating namespaces using ns 39 Loading other namespaces 40 with .-require Loading and creatingmappings with :use 40 Creating mappings with .refer 41 LoadingJava classes with .import 42 *

*

*

2.10

Summary

Dipping our toes 3.1

42

in the pool

Truthiness

44

Wfiat's truth?

nil 3.2

versus

43

false

Nil pun with

44

*

Don't create Boolean

45

care

45

objects

44

xi

CONTENTS

3.3

Your

assignment,

Destructuring Destructuring

Using

should you choose to accept it

with

47

a vector

in function

methods

accessor

3.4

47

Destructuring

the REPL to

1^I. 2

Destructuring

parameters

50*

with

a

map

49

Destructuring versus

51

experiment *

Summary

47

50

Experimenting with seqs 51 Putting it all together 54 fust forfun 56 3.5



Experimenting with graphics things go wrong 54

52

When

56

D.A.T.A. ^JPYIPIi(S& •«««»««»«tt«»*««*e««0*«»**««»««»«»«*»c«*»«»»««»»0**»««»0159 On scalars 4.1

61

Understanding precision Truncation

Trying

Why be rational? rationality 67 4.3

When

to use

How

are

66

66

*

71

73

Summary

*

Symbols

Functions

68'

Qualifying your

and

71

namespaces

*

74

77

"

means.



Beware

Lisp-1

72

73

of mutable matchers

75

75

keep using

Vectors:

of

70

76

Persistence, sequences, and

Big-0

Caveats

68

Regular expressions—the second problem

"You

5.2

How to be rational

*

keywords

Composite data types 5.1

65

Symbolic resolution

Syntax 4.6

64

Overflow 64

69

Metadata

4.5

*

keywords different from symbols?

keywords 4.4

63

Rounding errors

*

be rational

to

62

Promotion

*

64

Underflow 4.2

62

*

complexity

that word. I do not think it

Sequence

terms and what

77 what you think it 78 mean

means

they

81

creating and using them in all their varieties 82

Building vectors

*

Large

vectors

83

Vectors

Using vectors instead of reverse 87* Subvectors MapEntries 88 What vectors aren't 89 *

as

88*

82

stacks Vectors

86 as

xii

CONTENTS

5.3

Lists:

Clojure's code form data

How

to use

93

things Persistent B asic

*

stacks

91

What lists

*

*

92

on

*

Getting

94 94

properties of Clojure sets 94

95

contains?

*

Keeping your sets in



order with

96

closure.set

*

97

in maps

Thinking

91

nothing 92 Putting things Taking things off 93

sets

sorted-set 5.6

as

persistent queues

A queue about

5.5

Lists

*

91

arm't

5.4

90

Lisps like

Lists like

90

structure

Hash maps

97* Keeping your keys in order with sorted maps Keeping your insertions in order with array maps 100 5.7

Putting it all together: finding in

a

Part 3

sequence

Being lazy 6.1

On

101

6.2

Designing

a

6.3

Laziness

113

108* Being set in your ways—

115

recipe

6.5

Summary

logical-and

Losing your

*

all

together:

a

*

117

Understanding the lazyEmploying infinite *

macros

lazy quicksort

119

121

124

Functional programming

125

Functions in all their forms First-class functions

126

Pure functions

*

functions

113

head

118* The delay and force

sequences

Putting it

110

persistent toy

Familiar laziness with

6.4

107

107

immutability

Defining immutability immutability 109

7.1

105

programming

and set in your ways

seq

of items

103

Summary

Functional

position

101

Implementation 5.8

the

99

with

131

pre-

and

*

126

Higher-order functions

Named

arguments

postconditions

133

132*

129

Constraining

xiii

CONTENTS

7.2

Closures

7.3

Thinking recursively

135

Mundane recursion

141 142* 146

forget your trampoline 7.4

Putting The A

it all *

I\\RF 4

151

implementation

143

recur

Don't 148

Continuation-Massing style

together: A* pathfinding

149

Notes about the A

*

*

154

implementation 7.5

Tail calls and *

154

Summary

LAlRGli^SCAJLIi. Dl^SION««*«««*»«»»»«»««***««a««*«i*«««««»»«»«»« 155 Macros 8.1

157

Data is code is data

158 and

Syntax-quote, unquote, thumb

8.2

160

splicing

*

Macro rules

of

161

Defining control Defining

161

structures

control structures without syntax-quote

162

Defining control structures using syntax-quote and unquoting 8.3

Macros

combining forms

8.4

Using macros

to

change

forms

8.5

Using macros

to

control

symbolic

170*

Anaphora capturing 8.6

Using

8.7

Putting

8.8

Summary

9.1

164 165 resolution time

(Arguably) useful selective name

it all

manage

together:

macros

and code

177

178 179

Creating namespaces

*

Expose only

parts

184

*

188

180

183

Usage

185* Multimethods to the rescue

Ad hoc hierarchiesfor inherited behaviors in hierarchies

what's needed

182

multimethods with the Universal

Exploring Clojure Design Pattern

power

173

returning functions

176

Namespaces

The

171

resources

Declarative inclusions and exclusions

9.2

169

171

macros to

Combining data

163

187

*

186

*

185

Resolving conflict

Arbitrary dispatchfor true maximum

CONTENTS

9.3

Types, protocols, Records

189* Protocols

base with

9.4

and records

Putting it

deftype

all

a

more

primitive

together:

fluent builder for chess

a

202

moves

202

204

Clojure implementation

207

Generating objects A

10.2

Building from

206

Summary

Java.next 10.1

192*

200

Java implementation 9.5

189

on

simple dynamic web

the

fly with proxy

service

208

209

Clojure gen-class and GUI programming

212

Namespaces as class specifications 212 Exploring user interface design and development with Clojure 215 •

10.3

Clojure's relationship

to

Java arrays

Types of arrays: primitive and reference Thai unfortunate naming convention arrays 10.4

All

222

218 218 221

Array mutability

*

Multidimensional

Variadic method/constructor calls

*

Clojure functions implement...

222

222

java.util.Comparator 223 java.lang.Runnable Java. util. concurrent. Callable 224 10.5

Using Clojure data 225

structures in

Java APIs

223

224

java.util.List java.lang.Comparable java.ulil.RandomAccess 226 java.util.Collection java.util.Set 10.6

defmterface

Be wary of

226

227

227

Generating interfaces 10.7

225

*

on

exceptions

the fly

227

229

A bit

of background regarding exceptions 230 Runtime versus compile-time exceptions 230 Handling exceptions 232 Custom exceptions 233

10.8

Summary

Mutation 11.1

«

233

234

Software transactional memory with multiversion 235 concurrency control and snapshot isolation Transactions

236

Embedded transactions

236

that STM makes easy 237 « Potential downsides The things that make STM unhappy 239

*

The

238

things

220

CONTENTS

11.2

When to

240

Refs

use

241

Coordinated, synchronous change using alter with commute

change Fixing unite-skew 11.3

When

244

xuith

245

ensure

an

When to

Sharing 11.5

11.6

When

Safe

mutation

locks

260

When

When

11.8

266

Parallelism

11.9

Vars and

256

in transactions

259*

UsingJava's explicit

265 265

promises

*

Callback API to

blocking

267

268 269

pmap

271

Summary

pcalts

*

269

270

dynamic binding

binding macro Creating anonymous

Parts

between send

When not to use

262

The

11.10

difference

252

Deterministic deadlocks

268

pvalues

248

261

promises

*

The

258

callbacks

to use

*

Using Atoms

*

through locking

Parallel tasks with API

255

to use futures as

Agent handling

threads

locks

to use

Futures

11.7

across

245 246

255

Atoms

use

249

Error

«

11.4

ref-set

Refs under stress

*

distributed concurrency models

In-process versus Controlling I/O with and send-off 251 Agents 254

Commutative



247

Agents

to use

Vulgar change with

*

Creating a named Var Dynamic scope

Vars

272

*

271 273

274

Tangential considerations

Advantages of type and returns

12.2

12.3

Transients

278 Type-hinting arguments Type-hinting objects 280

adornment

278

*

280

Ephemeral garbage

280

mutable collections

281

Chunked sequences

Regaining

2

*

Transients compare in

282

one-at-a-time laziness

283

efficiency

to

CONTENTS

12.4

Memoization

Re-examining 12.5

284 memoizalion

Understanding

285

A memoization protocol

285

287

coercion

First rule

of coercion: don't 288 Corollary: you 're probably not doing it right 288 Second rule of coercion: don't 290 Third rule of coercion: coerce a stable local 290 Fourth rule of *

*

coercion: watch your sizes only as a goal 290

12.6

DSLs

the way you think

ubiquitous DSL specification 294 DSLs

293

Putting parentheses around the Clojure's approach to

299

design patterns



Contracts programming

303

handling and debugging

Enor

13.5

handling

Fare thee well resources

index

292

298

useful techniques

A lack of

Error

truncate

A note about

Clojure'sfirst-class design patterns 13.4

of coercion:

298

Testing Some

13.3

rule

293

A

13.2

Fifth

291

Summary

Clojure changes 13.1

290

«

319

313

306

312



Debugging

303

306 308

301