Download the PHP package phunkie/phunkie-adt without Composer
On this page you can find all versions of the php package phunkie/phunkie-adt. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package phunkie-adt
Phunkie ADTs: Algebraic Data Types for PHP
"In computer programming, especially functional programming and type theory, an algebraic data type is a kind of composite type, i.e., a type formed by combining other types." — good old Wikipedia
Sum Types
In computer science sum type, is a data structure used to hold a value that could take on several different, but fixed, types. Only one of the types can be in use at any one time, and a tag field explicitly indicates which one is in use.
Let's say we want to create a type Weekday. We want it to be limited to the possible 7 days in the week: Sunday, Monday, Tuesday, Wednesday, Thursday, Friday and Saturday.
We could do that in a number of ways using typical imperative or Object Oriented techniques. We could use enums, constants grouped under an interface or inheritance.
At the moment PHP does not have enums, so that one is not a choice.
Grouping constants in a interface is a popular alternative, but it does not give any type safety.
When passing a weekday to a function I cannot specify the Weekday type as a type hint.
Finally we could try extending a super class or implementing a common interface.
Now we can type hint Weekday we passing it around:
There is, however, no way in PHP to guarantee that the interface won't be extended beyond the ones distributed with the library. Nothing stops a Pluto fan from:
And all of a sudden we can now order pizza in weird days. But fear not! Sum types is there to save us from that madness.
First we create a type constructor Weekday
. PHP only way to create hintable types is through classes. So, let's use
that.
Then we seal it. Let's use ImmutableSealed
to add immutablity while we are at
it
ImmutableSealed
requires us to tell what is the types the type constructor can create
We still need to create the sum types:
If we try to extend Weekday
outside the seal we get a type error.
TODO:
- Exhaustive analysis
- Generics/Kinds: First order, higher order
- Implementing Show, Eq, Ord
Final Notes
- Phunkie is alpha software and may not be used in production