HOME

TheInfoList



OR:

Clojure (, like ''closure'') is a
dynamic Dynamics (from Greek δυναμικός ''dynamikos'' "powerful", from δύναμις ''dynamis'' "power") or dynamic may refer to: Physics and engineering * Dynamics (mechanics) ** Aerodynamics, the study of the motion of air ** Analytical dynam ...
and
functional Functional may refer to: * Movements in architecture: ** Functionalism (architecture) ** Form follows function * Functional group, combination of atoms within molecules * Medical conditions without currently visible organic basis: ** Functional sy ...
dialect The term dialect (from Latin , , from the Ancient Greek word , 'discourse', from , 'through' and , 'I speak') can refer to either of two distinctly different types of Linguistics, linguistic phenomena: One usage refers to a variety (linguisti ...
of the
Lisp programming language Lisp (historically LISP) is a family of programming languages with a long history and a distinctive, fully parenthesized prefix notation. Originally specified in 1960, Lisp is the second-oldest high-level programming language still in common us ...
on the
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
platform. Like other Lisp dialects, Clojure treats code as data and has a
Lisp macro In computer programming, a macro (short for "macro instruction"; ) is a rule or pattern that specifies how a certain input should be mapped to a replacement output. Applying a macro to an input is known as macro expansion. The input and output ...
system. The current development process is
community A community is a social unit (a group of living things) with commonality such as place, norms, religion, values, customs, or identity. Communities may share a sense of place situated in a given geographical area (e.g. a country, village, tow ...
-driven, overseen by
Rich Hickey Rich Hickey is a computer programmer and speaker, known as the creator of the Clojure programming language. Clojure is a Lisp dialect built on top of the Java Virtual Machine. He also created or designed ClojureScript and the Extensible Data ...
as its benevolent dictator for life (BDFL). Clojure advocates
immutability In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created.Goetz et al. ''Java Concurrency in Practice''. Addison Wesley Professional, 2006, Section 3.4 ...
and immutable data structures and encourages programmers to be explicit about managing identity and its states. This focus on programming with immutable values and explicit progression-of-time constructs is intended to facilitate developing more robust, especially
concurrent Concurrent means happening at the same time. Concurrency, concurrent, or concurrence may refer to: Law * Concurrence, in jurisprudence, the need to prove both ''actus reus'' and ''mens rea'' * Concurring opinion (also called a "concurrence"), a ...
, programs that are simple and fast. While its type system is entirely
dynamic Dynamics (from Greek δυναμικός ''dynamikos'' "powerful", from δύναμις ''dynamis'' "power") or dynamic may refer to: Physics and engineering * Dynamics (mechanics) ** Aerodynamics, the study of the motion of air ** Analytical dynam ...
, recent efforts have also sought the implementation of a dependent type system.


History and development process

Rich Hickey Rich Hickey is a computer programmer and speaker, known as the creator of the Clojure programming language. Clojure is a Lisp dialect built on top of the Java Virtual Machine. He also created or designed ClojureScript and the Extensible Data ...
is the creator of the Clojure language. Before Clojure, he developed dotLisp, a similar project based on the .NET platform, and three earlier attempts to provide interoperability between Lisp and
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
: a ''Java foreign language interface for
Common Lisp Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fro ...
'' (jfli), A ''Foreign Object Interface for Lisp'' (FOIL), and a ''Lisp-friendly interface to Java Servlets'' (Lisplets). Hickey spent about two and a half years working on Clojure before releasing it publicly in October 2007, much of that time working exclusively on Clojure with no outside funding. At the end of this time, Hickey sent an email announcing the language to some friends in the Common Lisp community. The development process is community-driven and is managed at the Clojure JIRA project page. General development discussion occurs at the Clojure Google Group. Anyone can submit issues and ideas at ask.clojure.org, but to contribute patches, one must sign the Clojure Contributor agreement. JIRA issues are processed by a team of screeners and finally Rich Hickey approves the changes. Clojure's name, according to Hickey, is a
word play Word play or wordplay (also: play-on-words) is a literary technique and a form of wit in which words used become the main subject of the work, primarily for the purpose of intended effect or amusement. Examples of word play include puns, phonet ...
on the programming concept " closure" incorporating the letters C, L, and J for C#,
Lisp A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech. Types * A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lisping ...
, and
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
respectively—three languages which had a major influence on Clojure's design.


Design philosophy

Rich Hickey developed Clojure because he wanted a modern
Lisp A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech. Types * A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lisping ...
for
functional programming In computer science, functional programming is a programming paradigm where programs are constructed by Function application, applying and Function composition (computer science), composing Function (computer science), functions. It is a declar ...
, symbiotic with the established
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
platform, and designed for
concurrency Concurrent means happening at the same time. Concurrency, concurrent, or concurrence may refer to: Law * Concurrence, in jurisprudence, the need to prove both ''actus reus'' and ''mens rea'' * Concurring opinion (also called a "concurrence"), a ...
. Clojure's approach to
state State may refer to: Arts, entertainment, and media Literature * ''State Magazine'', a monthly magazine published by the U.S. Department of State * ''The State'' (newspaper), a daily newspaper in Columbia, South Carolina, United States * ''Our S ...
is characterized by the concept of identities, which are represented as a series of immutable states over time. Since states are immutable values, any number of workers can operate on them in parallel, and concurrency becomes a question of managing changes from one state to another. For this purpose, Clojure provides several mutable
reference type In computer programming, data types can be divided into two categories: value types (or by-value types) and reference types (or by-reference types). Value types are completely represented by their meaning, while reference types are references to ano ...
s, each having well-defined semantics for the transition between states.


Language overview

Clojure runs on the
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
platform and as a result, integrates with
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
and fully supports calling Java code from Clojure, and Clojure code can be called from Java, too. The community uses tools like Leiningen for project automation, providing support for
Maven MAVEN is an American spacecraft orbiting Mars to study the loss of its atmospheric gases to space, providing insight into the history of the planet's climate and water. The spacecraft name is an acronym for "Mars Atmosphere and Volatile Evolu ...
integration. Leiningen handles project package management and dependencies and is configured using Clojure syntax. Like most other Lisps, Clojure's syntax is built on
S-expression In computer programming, an S-expression (or symbolic expression, abbreviated as sexpr or sexp) is an expression in a like-named notation for nested list (tree-structured) data. S-expressions were invented for and popularized by the programming la ...
s that are first parsed into data structures by a reader before being compiled. Clojure's
reader A reader is a person who reads. It may also refer to: Computing and technology * Adobe Reader (now Adobe Acrobat), a PDF reader * Bible Reader for Palm, a discontinued PDA application * A card reader, for extracting data from various forms of ...
supports literal syntax for
maps A map is a symbolic depiction emphasizing relationships between elements of some space, such as objects, regions, or themes. Many maps are static, fixed to paper or some other durable medium, while others are dynamic or interactive. Although ...
, sets and vectors in addition to lists, and these are compiled to the mentioned structures directly. Clojure is a
Lisp-1 Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fro ...
and is not intended to be code-compatible with other dialects of Lisp, since it uses its own set of data structures incompatible with other Lisps. As a Lisp dialect, Clojure supports functions as first-class objects, a
read–eval–print loop A read–eval–print loop (REPL), also termed an interactive toplevel or language shell, is a simple interactive computer programming environment that takes single user inputs, executes them, and returns the result to the user; a program written ...
(REPL), and a macro system. Clojure's
Lisp macro In computer programming, a macro (short for "macro instruction"; ) is a rule or pattern that specifies how a certain input should be mapped to a replacement output. Applying a macro to an input is known as macro expansion. The input and output ...
system is very similar to that of
Common Lisp Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fro ...
with the exception that Clojure's version of the
backquote The backtick is a typographical mark used mainly in computing. It is also known as backquote, grave, or grave accent. The character was designed for typewriters to add a grave accent to a (lower-case) base letter, by overtyping it atop that let ...
(termed "syntax quote") qualifies symbols with their
namespace In computing, a namespace is a set of signs (''names'') that are used to identify and refer to objects of various kinds. A namespace ensures that all of a given set of objects have unique names so that they can be easily identified. Namespaces ...
. This helps prevent unintended name capture, as binding to namespace-qualified names is forbidden. It is possible to force a capturing macro expansion, but it must be done explicitly. Clojure does not allow user-defined reader macros, but the reader supports a more constrained form of syntactic extension. Clojure supports
multimethods Multiple dispatch or multimethods is a feature of some programming languages in which a function or method can be dynamically dispatched based on the run-time (dynamic) type or, in the more general case, some other attribute of more than one of ...
and for
interface Interface or interfacing may refer to: Academic journals * ''Interface'' (journal), by the Electrochemical Society * ''Interface, Journal of Applied Linguistics'', now merged with ''ITL International Journal of Applied Linguistics'' * '' Inte ...
-like abstractions has a
protocol Protocol may refer to: Sociology and politics * Protocol (politics), a formal agreement between nation states * Protocol (diplomacy), the etiquette of diplomacy and affairs of state * Etiquette, a code of personal behavior Science and technology ...
based polymorphism and data type system using
records A record, recording or records may refer to: An item or collection of data Computing * Record (computer science), a data structure ** Record, or row (database), a set of fields in a database related to one entity ** Boot sector or boot record, ...
, providing high-performance and dynamic polymorphism designed to avoid the expression problem. Clojure has support for lazy sequences and encourages the principle of
immutability In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created.Goetz et al. ''Java Concurrency in Practice''. Addison Wesley Professional, 2006, Section 3.4 ...
and
persistent data structure In computing, a persistent data structure or not ephemeral data structure is a data structure that always preserves the previous version of itself when it is modified. Such data structures are effectively immutable, as their operations do not (v ...
s. As a
functional language In computer science, functional programming is a programming paradigm where programs are constructed by applying and composing functions. It is a declarative programming paradigm in which function definitions are trees of expressions that m ...
, emphasis is placed on
recursion Recursion (adjective: ''recursive'') occurs when a thing is defined in terms of itself or of its type. Recursion is used in a variety of disciplines ranging from linguistics to logic. The most common application of recursion is in mathematics ...
and
higher-order functions In mathematics and computer science, a higher-order function (HOF) is a function that does at least one of the following: * takes one or more functions as arguments (i.e. a procedural parameter, which is a parameter of a procedure that is itself ...
instead of side-effect-based looping. Automatic
tail call In computer science, a tail call is a subroutine call performed as the final action of a procedure. If the target of a tail is the same subroutine, the subroutine is said to be tail recursive, which is a special case of direct recursion. Tail recur ...
optimization is not supported as the JVM does not support it natively; it is possible to do so explicitly by using the recur keyword. For
parallel Parallel is a geometric term of location which may refer to: Computing * Parallel algorithm * Parallel computing * Parallel metaheuristic * Parallel (software), a UNIX utility for running programs in parallel * Parallel Sysplex, a cluster of IBM ...
and
concurrent Concurrent means happening at the same time. Concurrency, concurrent, or concurrence may refer to: Law * Concurrence, in jurisprudence, the need to prove both ''actus reus'' and ''mens rea'' * Concurring opinion (also called a "concurrence"), a ...
programming Clojure provides
software transactional memory In computer science, software transactional memory (STM) is a concurrency control mechanism analogous to database transactions for controlling access to shared memory in concurrent computing. It is an alternative to lock-based synchronization. STM ...
, a reactive agent system, and
channel Channel, channels, channeling, etc., may refer to: Geography * Channel (geography), in physical geography, a landform consisting of the outline (banks) of the path of a narrow body of water. Australia * Channel Country, region of outback Austral ...
-based concurrent programming. Clojure 1.7 introduced reader conditionals by allowing the embedding of Clojure and ClojureScript code in the same namespace. Transducers were added as a method for composing transformations. Transducers enable higher-order functions such as
map A map is a symbolic depiction emphasizing relationships between elements of some space, such as objects, regions, or themes. Many maps are static, fixed to paper or some other durable medium, while others are dynamic or interactive. Although ...
and fold to generalize over any source of input data. While traditionally these functions operate on
sequences In mathematics, a sequence is an enumerated collection of objects in which repetitions are allowed and order matters. Like a set, it contains members (also called ''elements'', or ''terms''). The number of elements (possibly infinite) is called t ...
, transducers allow them to work on channels and let the user define their own models for transduction.


Extensible Data Notation

Extensible Data Notation, or edn, is a subset of the Clojure language intended as a data transfer format. It can be used to serialize and deserialize Clojure data structures, and Clojure itself uses a superset of edn to represent programs. edn is used in a similar way to
JSON JSON (JavaScript Object Notation, pronounced ; also ) is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and arrays (or other ser ...
or
XML Extensible Markup Language (XML) is a markup language and file format for storing, transmitting, and reconstructing arbitrary data. It defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. T ...
, but has a relatively large list of built-in elements, shown here with examples: * booleans: true, false * strings: "foo bar" * characters: \c, \tab * symbols: name * keywords: :key * integers: 123 * floating point numbers: 3.14 * lists: (a b 42) * vectors: b 42/code> * maps: * sets: # * nil: nil (a null-like value) In addition to those elements, it supports extensibility through the use of ''tags'', which consist of the character # followed by a symbol. When encountering a tag, the reader passes the value of the next element to the corresponding handler, which returns a data value. For example, this could be a tagged element: #myapp/Person , whose interpretation will depend on the appropriate handler of the reader. This definition of extension elements in terms of the others avoids relying on either convention or context to convey elements not included in the base set.


Alternative platforms

The primary platform of Clojure is
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
, but other target implementations exist. The most notable of these is ClojureScript, which compiles to
ECMAScript ECMAScript (; ES) is a JavaScript standard intended to ensure the interoperability of web pages across different browsers. It is standardized by Ecma International in the documenECMA-262 ECMAScript is commonly used for client-side scripting o ...
3, and ClojureCLR, a full port on the .NET platform, interoperable with its ecosystem. A survey of the Clojure community with 1,060 respondents conducted in 2013 found that 47% of respondents used both Clojure and ClojureScript when working with Clojure. In 2014 this number had increased to 55%, in 2015, based on 2,445 respondents, to 66%. Popular ClojureScript projects include implementations of the
React REACT or React may refer to: Science and technology *REACT (telescope), a telescope at Fenton Hill Observatory, New Mexico, US Computing * React (JavaScript library) , a JavaScript library for building user interfaces, from Facebook ** React Nati ...
library such as Reagent, re-frame, Rum, and Om.


Other Implementations

Other implementations of Clojure on different platforms include: * Babashka, Native Clojure scripting language leveraging GraalVM native image an
Small Clojure Interpreter
* CljPerl, Clojure atop
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
* ClojureCLR, Clojure on
CLR CLR may refer to: * Calcium Lime Rust, a household cleaning-product * California Law Review, a publication by the UC Berkeley School of Law * Tube_bending, Centerline Radius, a term in the tubing industry used to describe the radius of a bend * Cen ...
, the .Net virtual machine. * ClojureDart,
Extend Clojure's reach
to mobile & desktop apps b
porting Clojure to Dart and Flutter
* Clojerl, Clojure on
BEAM Beam may refer to: Streams of particles or energy *Light beam, or beam of light, a directional projection of light energy **Laser beam *Particle beam, a stream of charged or neutral particles **Charged particle beam, a spatially localized grou ...
, the Erlang virtual machine * clojure-py, Clojure in pure
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
* ClojureRS, Clojure on
Rust Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxide-hydroxide (FeO(OH ...
* ClojureScript, Compiler fo
Clojure that targets JavaScript
It emit
JavaScript code compatible with the advanced compilation
mode of th
Google Closure optimizing compiler
* Ferret, compiles to self-contained C++11 that can run on microcontrollers * jank, Clojure compatible language with gradual typing that is hosted in C++ on top of an LLVM-based JIT * Joker, an interpreter and linter written in Go * Las3r, a subset of Clojure that runs on the
ActionScript ActionScript is an object-oriented programming language originally developed by Macromedia Inc. (later acquired by Adobe). It is influenced by HyperTalk, the scripting language for HyperCard. It is now an implementation of ECMAScript (meaning i ...
Virtual Machine (the Adobe Flash Player platform) * Pixie, Clojure-inspired Lisp dialect written in
RPython PyPy () is an implementation of the Python programming language. PyPy often runs faster than the standard implementation CPython because PyPy uses a just-in-time compiler. Most Python code runs well on PyPy except for code that depends on CPytho ...
* Rouge, Clojure atop YARV in
Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sa ...


Popularity

With continued interest in functional programming, Clojure's adoption by software developers using the Java platform has continued to increase. The language has also been recommended by software developers such as Brian Goetz, Eric Evans,
James Gosling James Gosling (born May 19, 1955) is a Canadian computer scientist, best known as the founder and lead designer behind the Java programming language. Gosling was elected a member of the National Academy of Engineering in 2004 for the conceptio ...
, Paul Graham, and
Robert C. Martin Robert Cecil Martin (born 5 December 1952), colloquially called "Uncle Bob", is an American software engineer, instructor, and best-selling author. He is most recognized for developing many software design principles and for being a founder of t ...
. ThoughtWorks, while assessing functional programming languages for their Technology Radar, described Clojure as "a simple, elegant implementation of Lisp on the JVM" in 2010 and promoted its status to "ADOPT" in 2012. In the "JVM Ecosystem Report 2018" (which was claimed to be "the largest survey ever of Java developers"), that was prepared in collaboration by Snyk and Java Magazine, ranked Clojure as the 2nd most used programming language on the JVM for "main applications". Clojure is used in industry by firms such as
Apple An apple is an edible fruit produced by an apple tree (''Malus domestica''). Apple fruit tree, trees are agriculture, cultivated worldwide and are the most widely grown species in the genus ''Malus''. The tree originated in Central Asia, wh ...
,
Atlassian Atlassian Corporation () is an Australian software company that develops products for software developers, project managers and other software development teams. The company is domiciled in Delaware, with global headquarters in Sydney, Australi ...
,
Funding Circle Funding Circle is a commercial lender. Originally it was peer-to-peer lending marketplace that allows the public to lend money directly to small and medium-sized businesses. Through this exchange businesses access lower costs of financing than t ...
,
Netflix Netflix, Inc. is an American subscription video on-demand over-the-top streaming service and production company based in Los Gatos, California. Founded in 1997 by Reed Hastings and Marc Randolph in Scotts Valley, California, it offers a fil ...
,
Nubank Nubank is a Brazilian neobank and the largest fintech bank in Latin America. Its headquarters are located in São Paulo, Brazil. The company also has engineering offices in Berlin, Germany, Buenos Aires, Argentina, and an office in Mexico City, Me ...
,
Puppet A puppet is an object, often resembling a human, animal or Legendary creature, mythical figure, that is animated or manipulated by a person called a puppeteer. The puppeteer uses movements of their hands, arms, or control devices such as rods ...
, and
Walmart Walmart Inc. (; formerly Wal-Mart Stores, Inc.) is an American multinational retail corporation that operates a chain of hypermarkets (also called supercenters), discount department stores, and grocery stores from the United States, headquarter ...
as well as government agencies such as
NASA The National Aeronautics and Space Administration (NASA ) is an independent agency of the US federal government responsible for the civil space program, aeronautics research, and space research. NASA was established in 1958, succeeding t ...
. It has also been used for creative computing, including visual art, music, games, and poetry.


Tools

Tooling for Clojure development has seen significant improvement over the years. The following is a list of some popular IDEs and
text editor A text editor is a type of computer program that edits plain text. Such programs are sometimes known as "notepad" software (e.g. Windows Notepad). Text editors are provided with operating systems and software development packages, and can be us ...
s with plug-ins that add support for programming in Clojure: *
Atom Every atom is composed of a nucleus and one or more electrons bound to the nucleus. The nucleus is made of one or more protons and a number of neutrons. Only the most common variety of hydrogen has no neutrons. Every solid, liquid, gas, and ...
, with Chlorine *
Emacs Emacs , originally named EMACS (an acronym for "Editor MACroS"), is a family of text editors that are characterized by their extensibility. The manual for the most widely used variant, GNU Emacs, describes it as "the extensible, customizable, s ...
, with CIDER *
IntelliJ IDEA IntelliJ IDEA is an integrated development environment (IDE) written in Java (programming language), Java for developing computer software written in Java, Kotlin (programming language), Kotlin, Groovy (programming language), Groovy, and other ...
, with Clojure-Kit or Cursive (a free license is available for
non-commercial A non-commercial (also spelled noncommercial) activity is an activity that does not, in some sense, involve commerce, at least relative to similar activities that do have a commercial objective or emphasis. For example, advertising-free community ...
use) * Light Table * Vim, with fireplace.vim, vim-iced, or Conjure (Neovim only) *
Visual Studio Code Visual Studio Code, also commonly referred to as VS Code, is a source-code editor made by Microsoft with the Electron Framework, for Windows, Linux and macOS. Features include support for debugging, syntax highlighting, intelligent code complet ...
, with Calva or Clover In addition to the tools provided by the community, the official Clojure
CLI CLI may refer to: Computing * Call Level Interface, an SQL database management API * Command-line interface, of a computer program * Command-line interpreter or command language interpreter; see List of command-line interpreters * CLI (x86 instruc ...
tools have also become available on
Linux Linux ( or ) is a family of open-source Unix-like operating systems based on the Linux kernel, an operating system kernel first released on September 17, 1991, by Linus Torvalds. Linux is typically packaged as a Linux distribution, which ...
,
macOS macOS (; previously OS X and originally Mac OS X) is a Unix operating system developed and marketed by Apple Inc. since 2001. It is the primary operating system for Apple's Mac computers. Within the market of desktop and lapt ...
, and
Windows Windows is a group of several proprietary graphical operating system families developed and marketed by Microsoft. Each family caters to a certain sector of the computing industry. For example, Windows NT for consumers, Windows Server for serv ...
since Clojure 1.9.


Features by example

The following examples can be run in a Clojure REPL such as one started with the Clojure CLI tools or an online REPL such as one available on REPL.it.


Simplicity

Because of its strong emphasis on simplicity, Clojure programs typically consist of mostly functions and simple data structures (i.e., lists, vectors, maps, and sets): ;; A typical entry point of a Clojure program: ;; `-main` function (defn -main ; name args; (variable) parameters (println "Hello, World!")) ; body


Programming at the REPL

Like other Lisps, one of Clojure's iconic features is interactive programming at the REPL. Note that, in the following examples, ; starts a line comment and ;; => indicates the expected output: ; define a var (def a 42) ;; => #'user/a ; call a function named `+` (+ a 8) ;; => 50 ; call a function named `even?` (even? a) ;; => true ; define a function that returns the remainder of `n` when divided by 10 (defn foo (rem n 10)) ;; => #'user/foo ; call the function (foo a) ;; => 2 ; print the docstring of `rem` (doc rem) ;; => ------------------------- clojure.core/rem (
um div UM or um may refer to: Universities * U of M (disambiguation) or UM, abbreviation for various universities Businesses * Universal McCann, a global advertising and media agency * United Motors Company, a former name of American automotive parts ...
remainder of dividing numerator by denominator. ; print the source of `rem` (source rem) ;; => (defn rem "remainder of dividing numerator by denominator."
um div UM or um may refer to: Universities * U of M (disambiguation) or UM, abbreviation for various universities Businesses * Universal McCann, a global advertising and media agency * United Motors Company, a former name of American automotive parts ...
(. clojure.lang.Numbers (remainder num div)))


Names at runtime

Unlike other runtime environments where names get compiled away, Clojure's runtime environment is easily introspectable using normal Clojure data structures: ; define a var (def a 42) ;; => #'user/a ; get a map of all public vars interned in the `user` namespace (ns-publics 'user) ;; => ; reference the var via `#'` (reader macro) and ; its associated, namespace-qualified symbol `user/a` #'user/a ;; => #'user/a ; de-reference (get the value of) the var (deref #'user/a) ;; => 42 ; define a function (with a docstring) that ; returns the remainder of `n` when divided by 10 (defn foo "returns `(rem n 10)`" (rem n 10)) ;; => #'user/foo ; get the metadata of the var `#'user/foo` (meta #'user/foo) ;; =>


Code as data (homoiconicity)

Similar to other Lisps, Clojure is
homoiconic In computer programming, homoiconicity (from the Greek words ''homo-'' meaning "the same" and ''icon'' meaning "representation") is a property of some programming languages. A language is homoiconic if a program written in it can be manipulated as ...
(also known as "code as data"). In the example below, we can see how to write code that modifies code itself: ; call a function (code) (+ 1 1) ;; => 2 ; quote the function call ; (turning code into data, which is a list of symbols) (quote (+ 1 1)) ;; => (+ 1 1) ; get the first element on the list ; (operating on code as data) (first (quote (+ 1 1))) ;; => + ; get the last element on the list ; (operating on code as data) (last (quote (+ 1 1))) ;; => 1 ; get a new list by replacing the symbols on the original list ; (manipulating code as data) (map (fn
orm Orm (in Old Norse and in modern Danish, Swedish, Norwegian (bokmål and nynorsk) the word for "snake", "worm" or "dragon") became an Anglo-Saxon personal name during period of the Danelaw. Orm may also refer to: * Orm or Ormin, the author of ...
(case form 1 'one + 'plus)) (quote (+ 1 1))) ;; => (plus one one)


Expressive operators for data transformation

The threading macros (->, ->>, and friends) can syntactically express the abstraction of piping a collection of data through a series of transformations: (->> (range 10) (map inc) (filter even?)) ;; => (2 4 6 8 10) This can also be achieved more efficiently using transducers: (sequence (comp (map inc) (filter even?)) (range 10)) ;; => (2 4 6 8 10)


Thread-safe management of identity and state

A
thread-safe Thread safety is a computer programming concept applicable to multi-threaded code. Thread-safe code only manipulates shared data structures in a manner that ensures that all threads behave properly and fulfill their design specifications without uni ...
generator of unique serial numbers (though, like many other Lisp dialects, Clojure has a built-in gensym function that it uses internally): (def i (atom 0)) (defn generate-unique-id "Returns a distinct numeric ID for each call." [] (swap! i inc))


Macros

An anonymous subclass of java.io.Writer that doesn't write to anything, and a macro using it to silence all prints within it: (def bit-bucket-writer (proxy ava.io.Writer[] (write [buf] nil) (close [] nil) (flush [] nil))) (defmacro noprint "Evaluates the given `forms` with all printing to `*out*` silenced." [& forms] `(binding [*out* bit-bucket-writer] ~@forms)) (noprint (println "Hello, nobody!")) ;; => nil


Language interoperability with Java

Clojure was created from the ground up to embrace its host platforms as one of its design goals and thus provides excellent
language interoperability Language interoperability is the capability of two different programming languages to natively interact as part of the same system and operate on the same kind of data structures. There are many ways programming languages are interoperable with on ...
with Java: ; call an instance method (.toUpperCase "apple") ;; => "APPLE" ; call a static method (System/getProperty "java.vm.version") ;; => "12+33" ; create an instance of `java.util.HashMap` and ; add some entries (doto (java.util.HashMap.) (.put "apple" 1) (.put "banana" 2)) ;; => ; create an instance of `java.util.ArrayList` and ; increment its elements with `clojure.core/map` (def al (doto (java.util.ArrayList.) (.add 1) (.add 2) (.add 3))) (map inc al) ;; => (2 3 4) ; show a message dialog using Java Swing (javax.swing.JOptionPane/showMessageDialog nil "Hello, World!") ;; => nil


Software transactional memory

10 threads manipulating one shared data structure, which consists of 100 vectors each one containing 10 (initially sequential) unique numbers. Each thread then repeatedly selects two random positions in two random vectors and swaps them. All changes to the vectors occur in transactions by making use of Clojure's
software transactional memory In computer science, software transactional memory (STM) is a concurrency control mechanism analogous to database transactions for controlling access to shared memory in concurrent computing. It is an alternative to lock-based synchronization. STM ...
system: (defn run vecs nitems nthreads niters (let ec-refs (->> (* nvecs nitems) (range) (into [(comp (partition-all nitems) (map vec) (map ref)))) swap #(let [v1 (rand-int nvecs) v2 (rand-int nvecs) i1 (rand-int nitems) i2 (rand-int nitems)] (dosync (let [tmp (nth @(vec-refs v1) i1)] (alter (vec-refs v1) assoc i1 (nth @(vec-refs v2) i2)) (alter (vec-refs v2) assoc i2 tmp)))) report #(->> vec-refs (into [] (comp (map deref) (map (fn [v] (prn v) v)) cat (distinct))) (count) (println "Distinct:"))] (report) (->> #(dotimes niters(swap)) (repeat nthreads) (apply pcalls) (dorun)) (report))) (run 100 10 10 100000) ;; => 1 2 3 4 5 6 7 8 9 0 11 12 13 14 15 16 17 18 19 ... 90 991 992 993 994 995 996 997 998 999Distinct: 1000 82 318 466 963 619 22 21 273 45 596 08 639 804 471 394 904 952 75 289 778 ... 84 216 622 139 651 592 379 228 242 355Distinct: 1000 nil


See also

*
List of JVM languages This list of JVM Languages comprises notable computer programming languages that are used to produce computer software that runs on the Java virtual machine (JVM). Some of these languages are interpreted by a Java program, and some are compiled ...
*
List of CLI languages CLI languages are computer programming languages that are used to produce libraries and programs that conform to the Common Language Infrastructure (CLI) specifications. With some notable exceptions, most CLI languages compile entirely to the Com ...
*
Comparison of programming languages Programming languages are used for controlling the behavior of a machine (often a computer). Like natural languages, programming languages follow the rules for syntax and semantics. There are thousands of programming languages and new ones are c ...


References


Further reading

* * * * * * * * * * * * *


External links

* {{Authority control 2007 software Articles with example Clojure code Cross-platform free software Cross-platform software Dynamic programming languages Dynamically typed programming languages Extensible syntax programming languages Functional languages High-level programming languages JVM programming languages Lisp (programming language) Lisp programming language family Multi-paradigm programming languages Programming languages Programming languages created in 2007 Scripting languages Software using the Eclipse license Source-to-source compilers