DEV Community

Cover image for Mutability in Clojure
Marcos Henrique
Marcos Henrique

Posted on

Mutability in Clojure

Introduction

Clojure is Functional, What does that mean?

Functional language is a programming paradigm. Development is based on function results and programming is done with expressions, as if functions were objects. In this approach, the output value depends only on the input arguments. That way, it doesn't matter what environment or scenario the system is in. Thus, the output of the output is always the same for the same input arguments.

Simply put, this would be state-immutable programming, since functions have the same value and behavior throughout the process. Thus, functional language becomes totally inherent in situations of parallelism, distribution and very high competition and criticality.

Immutability X Mutability

Immutability

It's the quality of not being able to change.
A clear example is a ROM memory

Mutability

Characteristic of what is easily changeable or variable; also called variability;
A concise example is RAM memory

How it's work on Clojure?

By default every symbol in clojure is unchanging

(def myArray [1 2 3 4])

(print(update myArray conj 5)) ;returns 1 2 3 4 5

(print myArray) ;returns 1 2 3 4
Enter fullscreen mode Exit fullscreen mode

That is, when you try to add values ​​to a symbol you get a clone with the value added, a dumb way to persist with that value would be to set another symbol with that return as a value, but as we are clean coders we will not do that.
How could we have a persisted value then?

Atoms ⚛

Atoms provide a way to manage shared, synchronous, independent state. They are a reference type like refs and vars.

You create an atom with atom, and can access its state with deref/@.

Like refs and agents, atoms support validators. To change the value of an atom, you can use swap!.

A lower-level compare-and-set! is also provided.

Changes to atoms are always free of race conditions.

(def myArray (atom [1 2 3 4]))

(swap! update myArray conj 5)

(print myArray) ;returns a ref to an atom, is ugly to see

(print @myArray) ; prettier way to print an atom
Enter fullscreen mode Exit fullscreen mode

🚨 Every time you see ! in final of a method in Clojure, that's refer to side a effect.

Now You are able to use mutability and immutability in Clojure 🤓

Thanks to read, until the next!

Top comments (0)