The building blocks of FP: pure functions, immutability, and Referential transparency -Part 1-

Wikipedia gives the following definition of Functional programming
“In computer sciencefunctional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data”.
We can extract 2 main concepts from this definition
1- Mathematical functions are the way to do computation (they are first class citizens)
2- Don’t use mutable states
Now coming from the OOP world (.Net) i tend to agree on the first part (although the mathematical part is tricky), and mutable state is at a best a bother and a waste of time .

Pure Functions
Now the definitions of FP cites Mathematical Functions, we can describe it as follows: for the same input you will always get the same output, nothings out of the ordinary right! well hold your horses, lets see an example of a function in the imperative way:

var acc = 0 
def giveMeNumber() = {
  acc = acc + 1
  acc
}

Running giveMeNumber() twice will return 2 different results, the culprit is the acc, the function is using a variable that exists outside of its scope, an external input that the function doesn’t know about .
It’ called a Side cause.
Now imagine if acc was an immutable variable each time we call the giveMeNumber() it will create it’s own copy of it, thus returning the same result, this is where immutability can help us satisfy the mathematical definition.


The same case can be made if our function was making an external call as we can see in the below code

var acc = 0 
def giveMeNumber() = {
  acc = acc + 1
  DbService.Save(acc)
  acc
}

This function causes a change in the outside world (in this case world means the scope of the function), so it changes the state of the DB data, imagine another function that reads this DB data before and after it was changed, same input different output: Side effect

Does that mean you should not write into files, or access the outside of a function ?definitely no!
AS Simon Peyton-Jones, a major contributor to the functional programming language Haskell, said the following: “In the end, any program must manipulate state. A program that has no side effects whatsoever is a kind of black box. All you can tell is that the box gets hotter.
The idea is to separate the code creating side effect and the pure code.

More to come in part 2 https://wordpress.com/block-editor/post/codegonewild.net/60

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s