Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Clojure.pdf
Скачиваний:
17
Добавлен:
09.05.2015
Размер:
12.92 Mб
Скачать

Prepared exclusively for WG Custom Motorcycles

Of the new crop of languages appearing on the Java Virtual Machine, Clojure might be the most compelling. Because of its time-honored roots in Lisp, compelling new features, and clever ways of mixing these features with existing Java libraries, it will expand the way you think about writing code. Stu has written a masterwork, making both new and old concepts blend together into an accessible and thoughtprovoking tour of this elegant language. Read the first chapter, and you will be hooked.

David Bock

Principal, CodeSherpas, Inc.

Stuart has charted the smoothest path yet to Clojure fluency with this well-organized and easy-to-read book. He has a knack for creating simple and effective examples that demonstrate the language’s unique features and how they fit together.

Chris Houser

A primary Clojure contributor and clojure-contrib lib author

Not only a great reference for an exciting new language, this book establishes Clojure as a serious tool for working programmers.

Stuart Sierra

Author of several clojure-contrib libraries, including the test-is testing framework

Stu is passionate about finding better ways to develop software, and Programming Clojure shows it. This book shows rather than tells how and why Clojure can help you and, because of its tight integration with the Java platform, how you can leverage your investment in existing infrastructure and numerous Java APIs. I found the book extremely easy to read, with some of the most unique and interesting code examples in any technical book I’ve read.

Scott Leberknight

Chief architect, Near Infinity Corp.

Prepared exclusively for WG Custom Motorcycles

As someone following Clojure’s development closely before Programming Clojure was available, I was very impressed with how much I learned by reading it. Stuart’s organized approach, excellent flow from introductory to more in-depth treatments, fine examples, and light spicing with humor conspire to make it both very informative and a real pleasure to read.

Stephen C. Gilardi

Principal author of clojure.core/[require,use] and clojure.main

Clojure is a surprisingly mature and polished language, given its youth, and Stuart’s book is a surprisingly mature and polished guide to such new and not yet widely charted territory. Any new language seeking to build adoption would be lucky to have such a resource so early.

Jerry Kuch

Software architect, Purple Iguana, Inc.

Stu’s approach restores the balance of programmer over language by providing both the blade to free us from Java’s syntactic straitjacket and the Lisp-based chains to make the JVM do our bidding. Whether your favorite part is Stu’s coverage of multimethods, his careful development of the Lancet build tool, or his alchemy-free discussion of macros, you will find that Programming Clojure has earned its place on the “close shelf” alongside Dybvig’s The Scheme Programming Language and Seibel’s Practical Common Lisp.

Jeremy J. Sydik

Director of Research Technology Development, University of Nebraska-Lincoln Center for Instructional Innovation

In the land of multicore, functional programming, concepts are vital, and concurrent languages like Clojure are increasingly important.

If you’ve avoided Lisp languages because of confusing syntax, take heart; Stu clearly and effectively explains this variant. Don’t worry, parentheses don’t bite!

Nathaniel T. Schutta

Author, speaker, teacher

Prepared exclusively for WG Custom Motorcycles

Prepared exclusively for WG Custom Motorcycles

Programming Clojure

Stuart Halloway

The Pragmatic Bookshelf

Raleigh, North Carolina Dallas, Texas

Prepared exclusively for WG Custom Motorcycles

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf and the linking g device are trademarks of The Pragmatic Programmers, LLC.

Every precaution was taken in the preparation of this book. However, the publisher assumes no responsibility for errors or omissions, or for damages that may result from the use of information (including program listings) contained herein.

Our Pragmatic courses, workshops, and other products can help you and your team create better software and have more fun. For more information, as well as the latest Pragmatic titles, please visit us at

http://www.pragprog.com

Copyright © 2009 Stuart Halloway.

All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher.

Printed in the United States of America.

ISBN-10: 1-934356-33-6

ISBN-13: 978-1-934356-33-3

Printed on acid-free paper.

P1.0 printing, May 2009

Version: 2009-5-27

Prepared exclusively for WG Custom Motorcycles

Contents

Foreword

 

 

 

10

Acknowledgments

 

 

12

Preface

 

 

 

14

 

Who This Book Is For

. . . . . . .

. . . . . . . . . . . . . . . . .

15

 

What Is in This Book

. . . . . . .

. . . . . . . . . . . . . . . . .

15

 

How to Read This Book . . . . . .

. . . . . . . . . . . . . . . . .

16

 

Notation Conventions

. . . . . . .

. . . . . . . . . . . . . . . . .

18

 

Web Resources and Feedback . .

. . . . . . . . . . . . . . . . .

19

 

Downloading Sample Code . . . .

. . . . . . . . . . . . . . . . .

20

1

Getting Started

 

 

21

 

1.1

Why Clojure? . . . . . . . .

. . . . . . . . . . . . . . . . .

21

 

1.2

Clojure Coding Quick Start

. . . . . . . . . . . . . . . .

30

 

1.3

Exploring Clojure Libraries

. . . . . . . . . . . . . . . .

37

 

1.4

Introducing Lancet . . . .

. . . . . . . . . . . . . . . . .

42

 

1.5

Wrapping Up . . . . . . . .

. . . . . . . . . . . . . . . . .

44

2

Exploring Clojure

 

 

45

 

2.1

Forms . . . . .

. . . . . . .

. . . . . . . . . . . . . . . . .

45

 

2.2

Reader Macros

. . . . . . .

. . . . . . . . . . . . . . . . .

55

 

2.3

Functions . . .

. . . . . . .

. . . . . . . . . . . . . . . . .

56

2.4Vars, Bindings, and Namespaces . . . . . . . . . . . . . 60

2.5

Flow Control . . . . . . . . . . . . . .

. . . . . . . . . . .

67

2.6

Where’s My for Loop? . . . . . . . . .

. . . . . . . . . . .

70

2.7Metadata . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

2.8 Wrapping Up . . . . . . . . . . . . . . . . . . . . . . . . . 77

Prepared exclusively for WG Custom Motorcycles

CONTENTS 8

3 Working with Java

79

3.1 Calling Java . . . . . . . . . . . . . . . . . . . . . . . . .

80

3.2Optimizing for Performance . . . . . . . . . . . . . . . . 88

3.3Creating and Compiling Java Classes in Clojure . . . . 94

3.4

Exception Handling . . . . . . . . . .

. . . . . . . . . . .

101

3.5

Adding Ant Projects and Tasks to Lancet . . . . . . . .

105

3.6Wrapping Up . . . . . . . . . . . . . . . . . . . . . . . . . 110

4 Unifying Data with Sequences

111

4.1 Everything Is a Sequence . . . . . .

. . . . . . . . . . . 112

4.2Using the Sequence Library . . . . . . . . . . . . . . . . 117

4.3Lazy and Infinite Sequences . . . . . . . . . . . . . . . . 125

4.4

Clojure Makes Java Seq-able . . . . . . . . . . . . . . .

127

4.5

Calling Structure-Specific Functions . . . . . . . . . . .

133

4.6Adding Properties to Lancet Tasks . . . . . . . . . . . . 141

4.7Wrapping Up . . . . . . . . . . . . . . . . . . . . . . . . . 146

5 Functional Programming

147

5.1Functional Programming Concepts . . . . . . . . . . . . 148

5.2

How to Be Lazy . . . . . . . . . . . .

. . . . . . . . . . .

152

5.3

Lazier Than Lazy . . . . . . . . . . .

. . . . . . . . . . .

160

5.4

Recursion Revisited . . . . . . . . . .

. . . . . . . . . . .

167

5.5Wrapping Up . . . . . . . . . . . . . . . . . . . . . . . . . 176

6 Concurrency

 

177

6.1

The Problem with Locks . . . . . . .

. . . . . . . . . . .

178

6.2

Refs and Software Transactional Memory . . . . . . . .

179

6.3Use Atoms for Uncoordinated, Synchronous Updates . 186

6.4

Use Agents for Asynchronous Updates . . . . . . . . . .

187

6.5

Managing Per-Thread State with Vars . . . . . . . . . .

192

6.6

A Clojure Snake . . . . . . . . . . . .

. . . . . . . . . . .

196

6.7

Making Lancet Targets Run Only Once . . . . . . . . .

207

6.8Wrapping Up . . . . . . . . . . . . . . . . . . . . . . . . . 210

7 Macros

211

7.1 When to Use Macros . . . . . . . . .

. . . . . . . . . . . 211

7.2Writing a Control Flow Macro . . . . . . . . . . . . . . . 212

7.3

Making Macros Simpler . . . . . . .

. . . . . . . . . . .

218

7.4

Taxonomy of Macros . . . . . . . . .

. . . . . . . . . . .

224

7.5

Making a Lancet DSL . . . . . . . . .

. . . . . . . . . . .

233

7.6Wrapping Up . . . . . . . . . . . . . . . . . . . . . . . . . 243

Prepared exclusively for WG Custom Motorcycles

Report erratum

this copy is (P1.0 printing, May 2009)

CONTENTS 9

8 Multimethods

244

8.1Living Without Multimethods . . . . . . . . . . . . . . . 245

8.2Defining Multimethods . . . . . . . . . . . . . . . . . . . 247

8.3Moving Beyond Simple Dispatch . . . . . . . . . . . . . 249

8.4 Creating Ad Hoc Taxonomies . . . . . . . . . . . . . . . 251

8.5When Should I Use Multimethods? . . . . . . . . . . . . 255

8.6Adding Type Coercions to Lancet . . . . . . . . . . . . . 259

8.7Wrapping Up . . . . . . . . . . . . . . . . . . . . . . . . . 264

9 Clojure in the Wild

265

9.1Automating Tests . . . . . . . . . . . . . . . . . . . . . . 266

9.2 Data Access . . . . . . . . . . . . . . . . . . . . . . . . . 270

9.3Web Development . . . . . . . . . . . . . . . . . . . . . . 275

9.4Farewell . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283

A

Editor Support

284

B

Bibliography

285

 

Index

286

Prepared exclusively for WG Custom Motorcycles

Report erratum

this copy is (P1.0 printing, May 2009)

Foreword

We are drowning in complexity. Much of it is incidental—arising from the way we are solving problems, instead of the problems themselves. Object-oriented programming seems easy, but the programs it yields can often be complex webs of interconnected mutable objects. A single method call on a single object can cause a cascade of change throughout the object graph. Understanding what is going to happen when, how things got into the state they did, and how to get them back into that state in order to try to fix a bug are all very complex. Add concurrency to the mix, and it can quickly become unmanageable. We throw mock objects and test suites at our programs but too often fail to question our tools and programming models.

Functional programming offers an alternative. By emphasizing pure functions that take and return immutable values, it makes side effects the exception rather than the norm. This is only going to become more important as we face increasing concurrency in multicore architectures. Clojure is designed to make functional programming approachable and practical for commercial software developers. It recognizes the need for running on trusted infrastructure like the JVM and supporting existing investments made by customers in Java frameworks and libraries, as well as the immense practicality of doing so.

What is so thrilling about Stuart’s book is the extent to which he “gets” Clojure, because the language is targeted to professional developers just like himself. He clearly has enough experience of the pain points Clojure addresses, as well as an appreciation of its pragmatic approach. This book is an enthusiastic tour of the key features of Clojure, well grounded in practical applications, with gentle introductions to what might be new concepts. I hope it inspires you to write software in Clojure that you can look back at and say, “Not only does this do the job, but it does so in a robust and simple way, and writing it was fun too!”

—Rich Hickey

Creator of Clojure

Prepared exclusively for WG Custom Motorcycles

FOREWORD 11

Prepared exclusively for WG Custom Motorcycles

Report erratum

this copy is (P1.0 printing, May 2009)