Other Practical Monads
Learn about some practical monads, such as State, Writer, and List.
We'll cover the following...
The State monad
A shared global state is amenable to mutation. A horde of undesired (often unmitigated) side effects can permeate through the global state through the routines and variables that use it. The essence of the State monad is the storage of an initial state and mutation of an existing one, usually an offshoot of an initial state.
Press + to interact
<?phprequire __DIR__ . '/vendor/autoload.php';use Chemem\Bingo\Functional as f ;use Chemem\Bingo\Functional\{PatternMatching as p,Functors\Monads\State};const START_STATE = ['on' => false, 'val' => 0];function playGame(string $txt): State{return State\gets(fn (array $state) => (f\fold(fn (array $prevState, string $char) => (p\patternMatch(['"a"' => fn () => f\extend($prevState, ['on' => true,'val' => $prevState['val'] + 1,]),'"b"' => fn () => f\extend($prevState, ['on' => true,'val' => $prevState['val'] - 1,]),'"c"' => fn () => f\extend($prevState, ['on' => false,]),'_' => fn () => f\extend($prevState, ['on' => true,]),], $char)), str_split($txt),$state)));}print_r(State\evalState(playGame('abcaaacbbcabbab'), null)(START_STATE));// outputs [['on' => true, 'val' => 0], ['on' => false, 'val' => 0]]
The simple example above is a port of a Haskell snippet that demonstrates the usefulness of the State monad. The code in the snippet effectively mimics a game whose state, a boolean-integer pair, changes on each letter input. The structure is rather simple:
-
An
'a'
increments the state count by1
and sets the ...