Middle
Tell me about functional programming and its principles.
sobes.tech AI
Answer from AI
Functional programming (FP) is a programming paradigm that considers computation as the evaluation of mathematical functions, avoiding state and mutable data.
Core principles:
-
Pure functions: A function is considered pure if it:
- Always returns the same result given the same arguments.
- Has no side effects (does not modify global state, does not perform input/output, etc.).
<?php // Pure function function add(int $a, int $b): int { return $a + $b; } // Impure function (has a side effect - modifies a global variable) $count = 0; function increment_and_get(): int { global $count; $count++; return $count; } -
Immutability of data: Once created, data cannot be changed. Instead of modifying an existing object, a new one with the desired changes is created.
<?php // Example of immutability (not a strict language principle in PHP, but can be implemented) class ImmutablePoint { private int $x; private int $y; public function __construct(int $x, int $y) { $this->x = $x; $this->y = $y; } public function getX(): int { return $this->x; } public function getY(): int { return $this->y; } // Instead of changing, return a new object public function move(int $dx, int $dy): self { return new self($this->x + $dx, $this->y + $dy); } } $p1 = new ImmutablePoint(1, 2); $p2 = $p1->move(1, 1); // $p1 remains (1, 2), $p2 becomes (2, 3) -
Functions as first-class objects: Functions can be passed as arguments to other functions, returned from functions, assigned to variables.
<?php // Functions as variables $greeter = function(string $name): string { return "Hello, " . $name; }; echo $greeter("World"); // Output: Hello, World // Functions as arguments function apply_transform(array $data, callable $transform): array { $result = []; foreach ($data as $item) { $result[] = $transform($item); } return $result; } $numbers = [1, 2, 3]; $doubled_numbers = apply_transform($numbers, function(int $n): int { return $n * 2; }); // $doubled_numbers = [2, 4, 6] -
Absence of side effects: Computations do not affect the program's state outside their scope.
-
Declarativity: Focus is on what to compute rather than how.
Advantages:
- Improved testability (pure functions are easy to test).
- Simplification of parallelism (lack of mutable state reduces synchronization issues).
- Better debuggability.
- More predictable code behavior.