Functional Programming
By ikhlas firlana < ikhlas@firlana.com >
What is Functional Programming?
In computer science, functional 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.
- Wikipedia
Functional programming is a programming paradigm in which we try to bind everything
in pure mathematical functions style.
It is a declarative type of programming style. Its main focus is on “what to solve” in
contrast to an imperative style where the main focus is “how to solve”.
- geeksforgeeks
Why Functional Programming?
- Reason :
- A major goal of functional programming is to minimize side effects
- Better understanding.
- Testing and debugging is easier.
“ Complexity is anything that makes software
hard to understand or to modify”
How its Work?
With Concepts
- Immutable
- Pure Functional
- Function as first Class Entity
- ..
“ Complexity is anything that makes software
hard to understand or to modify”
Immutable
<?php
- An immutable object is an object that can't be modified after it's created
class Car
{
- Immutability is a central concept of functional programming because /**
without it, the data flow in your program is lossy * @var string
*/
private $color;
/**
* Car constructor.
*
* @param string $color
*/
public function __construct(string $color)
{
$this->color = $color;
}
/**
* @return string
*/
public function getColor(): string
{
return $this->color;
}
}
$car = new Car('red');
$car->color = ‘blue’; // error, it’s immutable variable
Pure Functional
- A pure function is a function where the return value is only determined
by its input values, without observable side effects.
- This is how functions in math work: Math.cos(x) will, for the same value
of x, always return the same result. Computing it does not change x.
Function as first Class Entity
- there are lot definition is this concept, some of them are
- functions can be passed as arguments
- functions can be returned as value from others function
- functions can be assigned to a variable
- functions can be stored in data structures
- This means the language supports passing functions as arguments to
other functions, returning them as the values from other functions, and
assigning them to variables or storing them in data structures
Thank You
Q&A
References
- https://firlana.com/blog/functional-programming/
- https://medium.com/@ifirlana/functional-programming-33
2e504b0c54
- https://en.wikipedia.org/wiki/Functional_programming
- https://lispcast.com/what-are-first-class-functions/
- https://stackblitz.com/edit/angular-http-client-123
-