I am new to functional programming. What I understood is functional programming is writing code using pure functions and without changing value of data.
Instead of changing value of variables we create new variables in functional programming when we need to update a variable.
Suppose we have a variable x
which represents the total number of HTTP requests made by the program. If we have two threads then I want the threads to increment x
whenever a HTTP request is made by any thread. If both threads make a different copy of the variable x
then how can they synchronize the value of x
. For example: if thread 1 make 10 HTTP requests and thread 2 made 11 HTTP requests then they will print 10 and 11 respectively but how would I print 21.
The literal meaning of Immutability is unable to change. In the Functional Programming world, we create values or objects by initializing them. Then we use them, but we do not change their values or their state. If we need, we create a new one, but we do not modify the existing object's state.
The functional model emphasizes immutable data. However, some imperative languages have some immutable data as well. For instance, Java strings are immutable.
In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created. This is in contrast to a mutable object (changeable object), which can be modified after it is created.
Some of the main benefits of immutable objects include: Improved readability - Because variables stay the same, code is simpler to understand and reason about (without a whole lot of commenting)
I can provide an answer for the clojure
case. In clojure
, if you need to co-ordinate access to shared state, there are constructs in the language that are designed to deal with these situations.
In this case, you could use an atom
to hold the value. Changes made to an atom
are atomic, and will be made optimistically by way of clojure's STM. Atoms are one of clojure's reference types. An atom is essentially a reference to a value, which can change over time in a controlled way via the atom's mutation functions.
See the clojure docs for more information on atoms and the other references types.
I will address the Haskell part. MVar
is one of the communication mechanism for threads. This is one of the example taken from Simon Marlow's book (the program is self-explanatory):
main = do
m <- newEmptyMVar
forkIO $ do putMVar m 'x'; putMVar m 'y'
r <- takeMVar m
print r
r <- takeMVar m
print r
The output for the above program will be:
'x'
'y'
You can see in the above example how the MVar
value in variable m
is shared between threads. You can learn more about these techniques in this book.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With