Articles with the tag Functional Programming

Lazy evaluation with PHP Generators


After learning different concepts from functional languages, I came to realize that some of them can be applied to PHP code as well. I lastly wrote a small library helping to process CSV data structures. I wrote functions to process collections of data to return Generators. PHP Generators are a kind of iterators, which generate values only as they are needed (i.e. the iterator generates values lazily). All of the functions are designed in a way that they can be combined to a "pipeline". The pipeline itself is a function which returns a Generator. This concept of combining functions to build more complex functions is also called function composition. This is a core concept of any functional programming language, most often there is a very elegant syntax for it. An example in Haskell:

numOfWords = length . words

Here, length is a function which takes a List and returns its size; and words is a function which splits a string into a List of words. I just defined a new function, numOfWords, which composes this two functions into a function which counts the number of words in a string.

While there is no such elegant syntax for this in PHP, the concept can still be applied. Under the hood, the . operator in Haskell is a function itself, which takes two functions as input, and returns a new function. PHP allows us to build such a function ourselves:

function compose($fnA, $fnB): \Closure
{
  return function ($input) use ($fnA, $fnB) {
    return $fnB( $fnA($input) );
  }
}

This does the same as the . function is haskell, except that it applies the functions from left to right instead of right to left. I think it's easier to understand this way in PHP code.

So, to summarize this introduction, we will talk about this two concepts in the following article:

  • lazy evaluation (using PHP Generators)
  • composing functions

If this concepts are new to you, at this point you're probably asking what advantages this concepts can bring to you. By explaining the code I wrote for my CSV Tools, I hope you see where this concepts can be used in the real world to improve PHP code.