paint-brush
Clojure Immutable and Persistent Data Structuresby@abhishekamralkar
1,003 reads
1,003 reads

Clojure Immutable and Persistent Data Structures

by Abhishek AmralkarNovember 21st, 2018
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Clojure is modern dialect of old school programming language named as LISP. Clojure strongly believes in Code as Data and Data as Code philosophy just like LISP. Clojure is a dynamic, general purpose programming language that runs in the Java Virtual Machine. Clojure emphasizes
featured image - Clojure Immutable and Persistent Data Structures
Abhishek Amralkar HackerNoon profile picture

What Clojure is?

Clojure is modern dialect of old school programming language named as LISP. Clojure strongly believes in Code as Data and Data as Code philosophy just like LISP. Clojure is a dynamic, general purpose programming language that runs in the Java Virtual Machine. Clojure emphasizes

Get Clojure set up

Clojure needs JVM as its runs on top of JVM. Make sure you have min Java 1.7 installed on your system

mkdir -p ~/bin && cd ~/bin 

curl -O https://raw.githubusercontent.com/technomancy/leiningen/stable/bin/lein 

chmod a+x lein

export PATH="$PATH":~/bin

or

curl -O https://download.clojure.org/install/linux-install-1.10.0.403.shchmod +x linux-install-1.10.0.403.shsudo ./linux-install-1.10.0.403.sh

Data Structures

4 fundamental Data Structure of Clojure.

  • List ()
  • Vector []
  • Sets #{}images
  • Maps {}

By Immutable means value of the collections will not change at any point of time, while adding, updating, removing elements from the collections, rather the output will be the new version of structure.

List in Clojure are the fundamentals. List in Clojure are linked list and first element in list is always evaluated as function call. Everything in between two braces in Clojure is list. List is useful when we want to get items from the top of the list.

Vectors [] are the default way to make sequences in Clojure. Vectors are heterogeneous. We can retrieve the items from them and also add them at the end and at the beginning. When we want to add new element in to the list the newest element will always get added at the end of the vector.

Retrieval in Clojure vectors is very fast.

Maps {} are extremely useful and widely used in Clojure to store the structured data in {:key value} format. To retrieve the value from the maps we can use get and also we can use keys as a function to retrieve the values from the maps which is more idiomatic way to retrieve from the maps.

Some useful functions can be used for maps operations are

  • get — To retrieve the values from the maps
  • assoc — To update the maps
  • dissoc — To remove the key/values from the maps
  • keys — To get all the keys in the map
  • vals — To get all the keys in the map
  • merge — To merge the multiple maps into one single map

Sets #{} are collections of unique values. No repetitions allowed.