Hello there!
I decided to write a little bit about FP which I know.
This time we will talk about Functional Programming
and one of it's concepts Pure Functions.
So, let's start what is Functional Programming itself?
As you can guess it's based upon functions and not which we are used to,
but math functions and the biggest difference here's the all math functions are pure and have a single argument.
So let me give an example:
function hello(string $name): string {
return "hello, $name!";
}
This function is pure, because it has following:
- It doesn't have side effects
- It's referentially transparent
What is a side effect? It's something that's done outside of scope of our function, e. g.: database queries, file writings, changing global variable values, etc. Example (to run in cli):
function hello(string $name): void {
echo "Hello, $name!";
}
hello('John'); // John
fclose(STDOUT);
hello('John'); // Nothing
So now we know, at least our function must not change state of our app to be pure,
What is RT? It's when our function depends on it's input (arguments) and produce the same output if you have given the same arguments.
And the first introduced function is referentially transparent, because no matter how many times we call it with the same arguments, we will receive the same result.
function hello(string $name): string {
return "hello, $name!";
}
hello('John') // John
hello('John'); // John
What benefits we gain?
- Easy to test
- Easy to understand
If somebody is interested in it, I will continue to cover this topic.
Top comments (2)
A pure function
Thank for addition, appreciate this! :)