Functional Programming with Phel ๐Ÿ˜

When PHP meets FP ๐Ÿš€๐Ÿš€๐Ÿš€๐ŸŒš

Jesus Valera Reales
2 min readFeb 1, 2021

--

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! ๐ŸŽ

https://phel-lang.org/

--

--

Jesus Valera Reales

Competitive, entrepreneur and autodidact. Hard worker, lover of technology and free software.

Recommended from Medium

Lists

See more recommendations