# Functional Programming with Phel ๐

## When PHP meets FP ๐๐๐๐

--

# What is Functional Programming?

Functional Programming (FP) is a programming paradigm that was created in the late 1950s. Itโs even older than Object-Oriented Programming (OOP).

The main concepts of this paradigm are:

*Pure functions*: The concrete input will produce always the same output.*Recursion*: There are no loops. In order to get this approach, the functions can call themselves using recursivity.*Functions are First-Class*: A function is treated as a variable, which means you can pass functions as function arguments.*Variables are immutables*: A variable cannot change its value once it is declared, but itโs possible to create new ones.

**Imperative vs Declarative**

Letโs start with the typical *factorial* example to explain the differences between those two terms in the programming world.

The factorial is the product of all positive integers less than or equal to a given positive number.

`n! = n * (n - 1) * (n - 2) * ... * 1`

Following this formula, we can assert that the factorial of 5 is:

`5! = 5 * 4 * 3 * 2 * 1`

But, if you noticed, the factorial of 5 is actually 5 times the factorial of 4.

`5! = 5 * 4!`

And the factorial of 4 is 4 times the factorial of 3โฆ and so on.

Itโs a *recursive* problem!

## Imperative programming

The developer describes the steps one-by-one to achieve the desired result.

function factorial(int $number): int

{

$factorial = 1;

while ($number >= 1) {

$factorial *= $number;

$number--;

} return $factorial;

}

We are overriding the `$factorial`

variable in every single iteration.

We focus on โ**HOWโ**.

## Declarative programming

The developer declares what the program does usually in small functions, with immutable variables, without side-effects using recursivity instead of loops if needed.

`(defn factorial`

[number]

(if (<= number 1)

1

(* number (factorial (- number 1)))))

As you probably may guess, FP uses a declarative paradigm.

We focus on โ**WHATโ**.

# Conclusion

FP is not better or worse than OOP, they are different but complementary in order to solve the same problem.

If you want to learn/practice with some FP, I definitely recommend you **Phel**.You can read more information here: Phel: the Lisp that compiles to PHP.

Version 0.1 has been recently released and I am sure you will have fun! ๐