Download the PHP package functional-php/pattern-matching without Composer
On this page you can find all versions of the php package functional-php/pattern-matching. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download functional-php/pattern-matching
More information about functional-php/pattern-matching
Files in functional-php/pattern-matching
Package pattern-matching
Short Description Pattern matching for PHP with automatic destructuring.
License BSD-3-Clause
Informations about the package pattern-matching
Pattern Matching
Pattern matching is the process of checking a series of token against a pattern.
It is different from pattern recognition as the match needs to be exact.
The process does not only match as a switch statement does, it also assigns the value
a bit like the list
construct in PHP, a process called destructuring.
Most functional languages implement it as a core feature. Here is are some small examples in Haskell:
If you want to read more about the topic, you can head over to Wikipedia : Pattern matching
Installation
composer require functional-php/pattern-matching
Basic Usage
As we cannot extend the syntax of PHP, the choice was made to use a syntax based on arrays. The key representes the pattern and the value is the function to call with the value or a constant if you want to do nothing with it.
Let's see how we could implement our 3 Haskell examples:
You can also use the match
function if you want to have a beefed up version of the switch
statement or if you don't like anonymous functions:
If you are just interested in destructuring your values, there is also a helper for that:
Patterns
Here is a quick recap of the available patterns:
Name | Format | Example |
---|---|---|
Constant | Any scalar value (int, float, string, boolean) | 1.0 , 42 , "test" |
Variable | identifier |
a , name , anything |
Array | [<pattern>, ..., <pattern>] |
[] , [a] , [a, b, c] |
Cons | (identifier:list-identifier) |
(x:xs) , (x:y:z:xs) |
Wildcard | _ |
_ |
As | identifier@(<pattern>) |
all@(x:xs) |
Testing
You can run the test suite for the library using:
composer test
A test report will be available in the reports
directory.
Contributing
Any contribution welcome :
- Ideas
- Pull requests
- Issues