Download the PHP package md/for-comprehension-preprocessor without Composer
On this page you can find all versions of the php package md/for-comprehension-preprocessor. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package for-comprehension-preprocessor
A for-comprenhensions pre-processor for PHP
For-comprenhensions are syntax sugar for composing certain group of operations that can be found in monadic collections: withEach
, withFilter
, filter
, map
and flatMap
. This pre-processor will translate the operations using the for-comprenhension syntax into pure PHP. This does not happen at runtime, so there is no hit on perfomance. The pre-processor works on top of the pre plugin and the yay macro library.
Let's see how it works in practice with iteration, filtering, mapping and flatmapping.
Iteration
gets translated to:
which prints
Ok, that's boring. PHP foreach does the same. Or does it? With this syntax you can do many iterations in one go.
which translates to:
and prints
Hmm! Starting to be interesting, huh? Oh! but's this is really nothing yet.
Mapping
When using the yield
keyword, one-liner for-comprehensions translate to mapping:
this becomes:
which produces a ImmList(2, 3, 4)
.
Flatmapping
You can compose these expressions to create bigger expressions. When you add lines to your for-comprehension you get them translated into flatMap
operations, only the last one remains a map
.
which gets translated into:
This is actually a very common pattern in functional programming and a very good way to keep operations within a pure context. The code below has no side effects and describes IO operations in a functional program.
Notice that you can use the wildcard _
to ignore the return values of operations. The yield ()
will return a IO<Unit>
. A unit is an empty product. If you are new to this, just think of it as a void
. It's not, but that would do for now.
Filtering
As we add operations to the for comprenhension we can add filters that will operate on the result of such operations, limiting what's given to the next operation.
this code is translated into:
The result is a new List with only the elements that satisfy the predicate $a % 2 == 0
or, in order words, are even.
A more complex example
which translate to:
We can also add the filters in the next line:
Which is the equivalent of having the filter next to the previous line.
Note that the pre-processor recognises tuples syntax, so you can return tuples and have them assigned to more than one varible:
which translate to:
or you can return tuples:
which maps to Some(Pair(42,43))
.
Final Notes
- This pre-processor is alpha software. Do not use it in production.
- You don't need to use a library like Phunkie to use this pre-processor, but you will need to provide with Tuples and an interface for your monadic collections implementing
withEach
,withFilter
,filter
,map
andflatMap
.