O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Clojure Programming Cookbook

Book Description

Handle every problem you come across in the world of Clojure programming with this expert collection of recipes

About This Book

  • Discover a wide variety of practical cases and real world techniques to enhance your productivity with Clojure.
  • Learn to resolve the everyday issues you face with a functional mindset using Clojure
  • You will learn to write highly efficient, more productive, and error-free programs without the risk of deadlocks and race-conditions

Who This Book Is For

This book is for Clojure developers who have some Clojure programming experience and are well aware of their shortcomings. If you want to learn to tackle common problems, become an expert, and develop a solid skill set, then this book is for you.

What You Will Learn

  • Manipulate, access, filter, and transform your data with Clojure
  • Write efficient parallelized code through Clojure abstractions
  • Tackle Complex Concurrency easily with Reactive Programming
  • Build on Haskell abstractions to write dynamic functional tests
  • Write AWS Lambda functions effortlessly
  • Put Clojure in use into your IoT devices
  • Use Clojure with Slack for instant monitoring
  • Scaling your Clojure application using Docker
  • Develop real-time system interactions using MQTT and websockets

In Detail

When it comes to learning and using a new language you need an effective guide to be by your side when things get rough. For Clojure developers, these recipes have everything you need to take on everything this language offers.

This book is divided into three high impact sections. The first section gives you an introduction to live programming and best practices. We show you how to interact with your connections by manipulating, transforming, and merging collections. You’ll learn how to work with macros, protocols, multi-methods, and transducers. We’ll also teach you how to work with languages such as Java, and Scala.

The next section deals with intermediate-level content and enhances your Clojure skills, here we’ll teach you concurrency programming with Clojure for high performance. We will provide you with advanced best practices, tips on Clojure programming, and show you how to work with Clojure while developing applications.

In the final section you will learn how to test, deploy and analyze websocket behavior when your app is deployed in the cloud. Finally, we will take you through DevOps. Developing with Clojure has never been easier with these recipes by your side!

Style and approach

This book takes a recipe-based approach by diving directly into helpful programming concepts. It will give you a foolproof approach to programming and teach you how to deal with problems that may arise while working with Clojure. The book is divided into three sections giving you the freedom skip to the section of your choice depending on the problem faced.

Downloading the example code for this book. You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the code file.

Table of Contents

  1. Clojure Programming Cookbook
    1. Clojure Programming Cookbook
    2. Credits
    3. About the Authors
    4. About the Reviewer
    5. www.PacktPub.com
      1. eBooks, discount offers, and more
        1. Why subscribe?
    6. Preface
      1. What this book covers
      2. What you need for this book
      3. Who this book is for
      4. Sections
        1. Getting ready
        2. How to do it…
        3. How it works…
        4. There's more…
        5. See also
      5. Conventions
      6. Reader feedback
      7. Customer support
        1. Downloading the example code
        2. Downloading the color images of this book 
        3. Errata
        4. Piracy
        5. Questions
    7. 1. Live Programming with Clojure
      1. Introduction
      2. REPL up!
        1. Getting ready
        2. How to do it...
        3. How it works...
        4. There's more...
        5. See also
      3. Working with primitive data types
        1. Getting ready
        2. How to do it...
          1. Using numbers
          2. Using strings and characters
          3. Using booleans and nil
          4. Using symbols and keywords
        3. How it works...
        4. There's more...
      4. Using bindings of vars, conditions, loops, and error handling
        1. Getting ready
        2. How to do it...
          1. def and let
          2. if and if-not
          3. when and when-not
          4. case and cond
          5. do and dotimes
          6. loop and recur
          7. try... catch... throw
        3. How it works...
      5. Using and defining functions
        1. Getting ready
        2. How to do it...
          1. Defining simple functions
          2. Defining variadic functions
          3. Defining multiple arity functions
          4. Defining functions that specify arguments using a keyword
          5. Defining functions with pre-condition and post-condition
        3. How it works...
        4. There's more...
      6. Using third-party libraries
        1. Getting ready
        2. How to do it...
          1. Adding the JAR file manually to your classpath
          2. Using Leiningen and a project.clj file
          3. Viewing dependencies
          4. one-off
          5. New dependencies at runtime
      7. Using namespaces
        1. Getting ready
        2. How to do it...
          1. Creating a new namespace
          2. Inspecting namespaces
          3. Adding functions with :import and :refer
          4. Loading namespaces from files
          5. Reloading namespaces
          6. How to organize namespaces
        3. There's more...
          1. Namespace for public API
          2. tools.namespace
      8. What's next?
    8. 2. Interacting with Collections
      1. Introduction
      2. Clojure collections and their basic functions
        1. Getting ready
        2. How to do it...
          1. Lists
          2. Vectors
          3. Maps
          4. Sets
        3. How it works...
          1. Clojure collections
          2. Differences between lists and vectors
          3. Clojure is immutable
        4. There's more...
          1. Converting collections between different types
          2. Using distinct
      3. Accessing and updating elements from collections
        1. Getting ready
        2. How to do it...
          1. Accessing collections using the nth function
          2. Accessing maps or sets using get
          3. Maps, sets, and keywords are functions to access collections
          4. Accessing a collection using second, next, ffirst, and nfirst
          5. Using update to update collections
        3. How it works...
        4. There's more...
          1. Using get for vectors
          2. Using collections as keys in maps
          3. Using get-in
          4. Using assoc-in
          5. Using update-in
      4. Filtering elements from collections
        1. Getting ready
        2. How to do it...
          1. Filtering multiples of three
          2. Filtering items of a map
          3. Filtering non-nil values
          4. Removing odd values from a sequence
          5. Using keep
          6. Using keep-indexed
        3. There's more...
          1. Filter as a transducer
          2. Filtering with core.async
      5. Transforming and sorting collections
        1. Getting ready
        2. How to do it...
          1. Using built-in sort
          2. Migrating to sort-by
          3. Using sorted-set
          4. Working with sorted collection subsets
          5. Sorting Clojure maps
          6. Sorted map structure
          7. Are you sorted yet?
        3. How it works...
        4. There's more...
          1. Sorting lines of a file
      6. Merging and splitting collections
        1. Getting ready
        2. How to do it...
          1. Using merge and merge-with for merging
          2. The zipmap merges keys and values for maps
          3. Using interleave
          4. Using split-at and split-with to split collections
        3. How it works...
        4. There's more...
          1. Using group-by to split collections
          2. Using the filter function to split collections
      7. How to become lazy
        1. Getting ready
        2. How to do it...
          1. The iterate function
          2. Realized?
          3. Random sequences with repeatedly
          4. Using the macro lazy-seq
        3. How it works...
        4. There's more...
          1. Other lazy-seq-producing functions
          2. Force evaluation with doall
          3. Lazy evaluation with files
          4. The map function and calling rest
    9. 3. Clojure Next
      1. Introduction
      2. Using destructuring techniques
        1. Getting ready
        2. How to do it...
          1. Sequential destructuring
          2. Using map destructuring
        3. How it works...
        4. There's more...
          1. Sequential destructuring for string
          2. Conditional destructing with core.match
      3. Using functional programming style
        1. Getting ready
        2. How to do it...
          1. Functions taking functions as their arguments
            1. map
            2. reduce
            3. apply
          2. Using anonymous functions
            1. Anonymous functions using fn
            2. Using function literals to define anonymous functions
          3. Functions returning functions
            1. constantly
            2. complement
            3. partial
            4. comp
            5. every-pred and some-fn
        3. How it works...
          1. Clojure functions are first-class functions
          2. Pure functions
        4. There's more...
          1. reduce and apply
          2. loop and recur
      4. Using threading macros
        1. Getting ready
        2. How to do it...
          1. Introducing the -> macro
          2. Introducing the ->> macro
          3. Introducing the cond-> and the cond->> macros
          4. Introducing some-> and some->>
        3. How it works...
        4. There's more...
          1. Introducing as->
          2. Flambo preview
      5. Defining simple macros
        1. Getting ready
        2. How to do it...
          1. Your first macro
          2. Your second macro
        3. How it works...
        4. There's more...
          1. Using quotes
          2. Macros everywhere
      6. Defining more advanced macros
        1. Getting ready
        2. How to do it...
          1. Tracking when code was started
          2. Logging a message with macro
        3. How it works...
        4. There's more...
          1. deftest
      7. Using protocols
        1. Getting ready
        2. How to do it...
          1. Defining a record
          2. Defining a type
          3. Defining a protocol
        3. How it works...
          1. Records and types are Java classes
          2. Differentiating between records and types
        4. There's more...
          1. Defining a mutable protocol and type
      8. Defining multimethods
        1. Getting ready
        2. How to do it...
          1. Defining a multimethod
        3. How it works...
        4. There's more...
      9. Transducers for dummies
        1. Getting ready
        2. How to do it...
        3. How it works...
          1. Composable functions
          2. Inserting elements
          3. Writing your own transducers
            1. Short circuit
        4. There's more...
          1. Transducers with core.async
          2. Summing things up
      10. Logic programming in Clojure
        1. Getting ready
          1. Baby logic steps
          2. Getting to know the "o" vocabulary
            1. conso: check for vector association
            2. resto: check for the rest of a vector
            3. membero
            4. appendo: appending list
            5. conde
            6. Matche
          3. Beginner logic
            1. Keeping fresh
            2. Finding only one result
          4. Mature logic
            1. Range of values
        2. How to do it...
          1. Generating data
          2. Generating more data with more logic variables
          3. Using a project
        3. How it works...
        4. There's more...
          1. Validating the results of a function
          2. Working with external data
    10. 4. File Access and the Network
      1. Introduction
      2. Manipulating files and directories
        1. Getting ready
        2. How to do it...
          1. spit and slurp
          2. Reader and writer with with-open
          3. Creating a file and directory
          4. Copying a file
          5. Deleting a file and a directory
          6. Listing files and directories in a directory
        3. How it works...
          1. slurp and spit
          2. with-open macro
        4. There's more...
          1. Reading HTTP resource
          2. Examining the source code
      3. Manipulating various formats of files - XML, JSON, YAML, and EDN
        1. Getting ready
        2. How to do it...
          1. XML
          2. JSON
          3. YAML isn't a markup language
          4. MessagePack, Clojure library
        3. How it works...
        4. There's more...
          1. Extensible Data Notation
      4. Making use of Clojure HTTP client
        1. Getting ready
        2. How to do it...
        3. How it works...
        4. There's more...
          1. async HTTP and core async
      5. Using queues and topics in the RabbitMQ
        1. Getting ready
          1. Installing RabbitMQ
        2. How to do it...
          1. Producing hello world messages and consuming them
            1. Declaring the namespace and loading Langohr libraries and IP address of the Docker container
            2. Defining a producer function
            3. Defining a message handler and consumer
            4. Testing producer and consumer
          2. Using blocking consumer
        3. How it works...
          1. Connect to broker and open channel
          2. How producer works
            1. Declaring queue
            2. Producing messages
          3. How consumer works
            1. Consumer messages
            2. Defining message handler
        4. There's more...
          1. Using fanout exchange
            1. fanout-producer
            2. fanout-consumer
            3. Running the fanout consumers
            4. Testing fanout consumers
          2. Using topic exchange
            1. Topic-publisher
            2. Topic-consumer
            3. Running the topic consumers
            4. Testing the topic consumers
        5. See also
      6. Using Kafka
        1. Getting ready
          1. Downloading Kafka 0.8.2.2
          2. Start ZooKeeper and Kafka server
          3. Create topic
          4. Run a console consumer
          5. Using clj-kafka
        2. How to do it...
          1. Declaring the namespace and load Clojure library
          2. Producing messages
          3. Consuming a messages
        3. How it works...
          1. Producing messages
          2. Consuming messages
        4. There's more...
          1. Creating a new topic
        5. See also
      7. Using MQTT
        1. Getting ready
          1. Installing the MQTT broker
            1. MQTT graphical client
            2. Send our first MQTT message
            3. Getting some Clojure
        2. How to do it...
        3. How it works...
        4. There's more...
      8. Streaming access to provide high performance
        1. Getting ready
        2. How to do it...
          1. Streaming out
          2. Streaming in
          3. Streaming with line-seq
        3. How it works...
        4. There's more...
      9. Using Apache Camel to connect everything
        1. Getting ready
        2. How to do it...
          1. Importing Camel classes
          2. Your first ride on Camel with Clojure
          3. Writing more Clojure idiomatic code with Camel
        3. How it works...
        4. There's more...
        5. See also
    11. 5. Working with Other Languages
      1. Introduction
      2. Calling Java methods and accessing Java objects from Clojure
        1. Getting ready
        2. How to do it...
          1. Instantiating objects
          2. Calling instance methods
          3. Calling class methods
          4. Accessing instance fields
          5. Accessing class fields
          6. Accessing inner classes
          7. Referencing classes
          8. Using arrays
        3. How it works...
          1. Summary of how Clojure accesses Java methods and objects
          2. Clojure does not inherit Java's checked exception
          3. Summary of array accesses
          4. Print strings of Java's primitives
        4. There's more...
          1. Chained calls with the double-dot macro
          2. Using the doto macro
          3. Using reflections
      3. Extending Java superclasses and implementing Java interfaces
        1. Getting ready
        2. How to do it...
          1. Using proxy
          2. Using reify for implementing interfaces
        3. How it works...
        4. There's more...
          1. Defining anonymous classes in Clojure
          2. Using annotations
      4. Calling Clojure from Java
        1. Getting ready
        2. How to do it...
          1. Defining a simple named class using gen-class
          2. Defining a class with instance methods and constructors in Clojure
          3. Creating a JAR file callable from Java
        3. How it works...
          1. The project.clj for generating Java classes
          2. AOT compilation
        4. There's more...
          1. Defining an interface and implementing a class callable from Java
            1. Using Maven for Clojure and Java projects
      5. Calling Scala from Clojure
        1. Getting ready
        2. How to do it...
          1. Using Leiningen to develop Scala and Clojure
            1. Importing Scala classes
            2. Calling instance methods
            3. Calling singleton methods
            4. Accessing tuples
            5. Accessing Scala fields
        3. How it works...
        4. There's more...
          1. Using SBT
            1. Creating an SBT-based project
            2. Writing source code
      6. ClojureCLR
        1. Getting ready
          1. Installing Visual Code Studio and creating a project
          2. Installing Mono Studio IDE
          3. Lein CLR
        2. How to do it...
          1. Calling .NET code from Clojure
            1. Starting an REPL
            2. Working with IO
            3. Parsing some XML using C# code
            4. Calling a REST API using Clojure/C#
            5. UI Prototyping
            6. Putting it all together
        3. How it works...
          1. Compiling Clojure code for .NET
            1. Adding Clojure code to a Visual Studio project
            2. Running Clojure code using Clojure.RT
            3. Using Xamarin Mono Studio
        4. There's more...
      7. ClojureScript
        1. Getting ready
        2. How to do it...
          1. Autocompiling your code
          2. Fibonacci'ed
        3. How it works...
          1. Interacting with JavaScript
          2. Using jQuery from ClojureScript
          3. Creating a ClojureScript library
          4. Using a third-party library
        4. There's more...
          1. Running in the REPL
          2. Compiling code for both Clojure and ClojureScript
    12. 6. Concurrency and Parallelism
      1. Introduction
      2. Solving concurrent problems using Clojure
        1. Getting ready
        2. How to do it...
          1. Using atoms
            1. Creating and referring atom
            2. Updating atom
            3. Using validator
            4. Using CAS operation
          2. Software Transactional Memory using ref and dosync
            1. Creating ref
            2. Updating refs using alter
            3. Using ensure
            4. Using watcher and a refined transaction code
            5. Using commute
          3. Using agents
            1. Creating agents
            2. Updating agents
        3. How it works...
          1. Summary of three reference types in Clojure
            1. Coordinated/uncoordinated
            2. Synchronous/asynchronous
          2. How STM works in Clojure
          3. Alter and commute
        4. There's more...
          1. promise and deliver
          2. pmap, pcalls, and pvalues
            1. pcalls
            2. pvalues
        5. See also
      3. Distributed actor-based dev with Akka
        1. Getting ready
        2. How to do it...
          1. Your first okku
          2. Creating actors
          3. Dispatching messages
        3. How it works...
          1. Actor system
          2. Understanding actors
        4. There's more...
          1. Calling remote actors
          2. Request and reply
        5. See also
      4. Using Spyglass and Couchbase to share state between JVMs
        1. Getting ready
          1. Setting up dependencies in project.clj
          2. Setting up Couchbase Server as a Memcached server
          3. Using docker-compose to start Couchbase Server
            1. Creating a directory and a file for docker-compose
            2. Start Couchbase cluster
            3. Check if Docker processes are running
          4. Summary of Couchbase cluster
          5. Using Couchbase web administrator console
            1. Logging into the web console
            2. Adding nodes to the cluster
            3. Adding Cluster
            4. Defining Memcached bucket
        2. How to do it...
          1. Defining to use Spyglass library
          2. Connecting server
          3. Set values
          4. Get values from another REPL
          5. Testing time to live
          6. Disconnecting
        3. How it works...
          1. What is Memcached?
          2. Access Memcached from Telnet
          3. Couchbase Server
        4. There's more...
          1. Using get-multi
          2. Using async-get
          3. Using CAS operations
        5. See also
      5. Reactive programming with meltdown
        1. Getting ready
        2. How to do it...
          1. Defining a reactor
          2. Sending a message to a reactor
          3. Going the sync way
        3. How it works...
          1. Selectors
          2. Streams
          3. Streams and reduce
          4. Combining functions with a graph
          5. Custom streams
        4. There's more...
      6. Bridging core.async
        1. Getting ready
          1. Memories - reviewing core.async basics
          2. Pub/sub
        2. How to do it...
          1. Async socket server
          2. Async socket client
          3. Chiming
        3. There's more...
          1. Client to Python WebSockets
          2. Clojure WebSocket server
      7. On Quasar/Pulsar
        1. Getting ready
        2. How to do it...
        3. How it works...
          1. Watching over other actors lifecycles
          2. State of an actor
        4. There's more...
          1. Blazar
    13. 7. Advanced Tips
      1. Introduction
      2. Hacking the Clojure code
        1. Getting ready
        2. How to do it...
        3. How it works...
        4. There's more...
      3. Using Reader Conditionals, compile to Clojure, and ClojureScript
        1. Getting ready
        2. How to do it...
          1. Your first Reader Conditional
          2. Using Reader Conditionals in namespaces
        3. How it works...
          1. The form of Reader Conditionals and Splice macros
          2. Macros in ClojureScript
        4. There's more...
          1. Building an application for Clojure and ClojureScript
            1. Adding a cljc file for demonstrating Quil
            2. Testing cljc code in both Clojure and ClojureScript
            3. Building and running a demo
        5. See also
      4. Real-time shared development with an REPL
        1. Getting ready
        2. How to do it...
          1. Shared REPLs
          2. Using Atom and proto-repl
          3. Using an embedded NREPL
        3. There's more...
          1. Custom REPL using Java interop
            1. Server
            2. Client
          2. The async custom REPL server
          3. Server REPL or more on real-time work on production code
      5. Declarative data descriptions and validations with plumatic/schema
        1. Getting ready
        2. How to do it...
          1. My first schema
          2. Using schema for records and other types
          3. Defining functions with validations
        3. How it works...
          1. Performance considerations
          2. Generating test data
        4. There's more...
          1. Data coercion with prismatic/schema
          2. Using core.typed
          3. core.spec
    14. 8. Web Applications
      1. Introduction
      2. Clojure with Vaadin - easy web widgets
        1. Getting ready
          1. Project settings
          2. The Clojure/Vaadin flow
        2. How to do it...
          1. Using the Calendar widget
          2. Reacting to events
          3. Clicking a button
          4. Using and reloading namespaces
          5. Server-side push
        3. There's more...
          1. Reactive Vaadin - ideas
          2. Reactive Vaadin - CPU monitoring
          3. Reactive Vaadin - Telegram on Raspberry Pi
          4. Deployment bonus
      3. Quickly create a REST API with Liberator
        1. Getting ready
        2. How to do it...
          1. Your first Liberator
          2. Using defresource
          3. Parameterized resources
          4. Defining GET/POST/PUT/DELETE methods for REST APIs
        3. How it works...
          1. Methods and status codes of HTTP
          2. Tracing requests
        4. There's more...
          1. Persistent REST resources using clojure.java.jdbc
            1. Preparing for jdbc
            2. Our service spec
            3. Creating a product table and defining access functions
            4. Defining resources and starting a server
            5. Accessing from an HTTP client
      4. Working with Immutant - reusing infrastructure
        1. Getting ready
        2. How to do it...
          1. Simple messaging with Artemis
          2. Remote messaging
          3. Remote procedure call with queues
          4. Scheduling code execution
          5. Piping and defining data transformation pipelines
          6. Using WebSockets made easy
        3. There's more...
          1. Packaging as standalone
          2. Packaging as a deployable web archive (WAR file)
      5. Developing with om.next, the next-generation ClojureScript library
        1. Getting ready
          1. Creating a new project for om.next
          2. Updating the om version
          3. Tips for dependencies
          4. Starting figwheel
        2. How to do it...
          1. Getting started with om.next
          2. Using states
        3. How it works...
          1. React fundamentals
            1. defui
            2. reconciler
          2. Life cycle of components
        4. There's more...
          1. Task list using om.next
            1. Defining the namespace and libraries to use
            2. Defining state
            3. Defining read
            4. Defining mutate
            5. Defining UIs
    15. 9. Testing
      1. Introduction
      2. Behavior-driven development
        1. Getting ready
          1. Dependencies
          2. The first feature
          3. Designing a folder structure to organize features
        2. How to do it...
          1. Many assumptions with tables
          2. Reading assumptions from a CSV file
          3. Doing it with Excel
          4. Doing it with web APIs and MongoDB
        3. There's more...
          1. VirtualBox
          2. Freactive
          3. Flambo, or BDD meets Apache Spark
          4. EEP for BDD
          5. OpenCV
      3. Testing with random inputs and pattern-based testing
        1. Getting ready
          1. Libraries
          2. Generating random values or groups of values
          3. Random values based on schema
        2. How to do it...
          1. Your first test.check specification
          2. Auto-running tests
          3. More specifications and generators
          4. Generators and de-structuring
          5. Herbert
        3. There's more...
      4. Benchmarking with Criterium, performance tips, and other tools
        1. Getting ready
        2. How to do it...
          1. Using Criterium
        3. How it works...
          1. Type hints
          2. Using appropriate data types
          3. Maps versus records versus types
          4. Primitive arrays
          5. Working with transient data structures
          6. Memoize functions
        4. There's more...
          1. Logging with timbre and profiling with tufte
          2. Using jvisualvm
    16. 10. Deployment and DevOps
      1. Introduction
      2. Riemann - monitoring deliverance and slacking
        1. Getting ready
          1. Installing the Riemann service
          2. Configuring the Riemann daemon
          3. The Riemann dashboard
          4. Riemann-health
          5. Just enough dashboard configuration
          6. Preparing to send events
        2. How to do it...
          1. Basic event reporting for a service
          2. Expiring events
        3. How it works...
        4. There's more...
          1. From Riemann to Slack webhooks
          2. From Slack bots to Riemann
      3. Deploying Clojure with Docker
        1. Getting ready
          1. Installing Docker on OS X or Windows
          2. Installing Docker on Debian
          3. Preparing the Clojure application
          4. Packaging the application into a JAR file
          5. Creating the Docker container
        2. How to do it...
          1. Connecting directly to a remote Docker
        3. There's more...
      4. Clojure on Amazon Web Services
        1. Getting ready
          1. Signing up on AWS
          2. Getting the access key and secret access key
          3. Setting up dependencies in your project.clj
        2. How to do it...
          1. Using EC2
          2. Using S3
          3. Using Amazon SQS
          4. Serverless Clojure with AWS Lambda
            1. Clojure namespace helloworld
            2. Hello World - the AWS part
            3. Hello Stream
            4. Real-world Lambdas
        3. How it works...
          1. What is Amazon EC2?
          2. Amazon S3
            1. Buckets and keys
            2. Objects
        4. There's no more...