Skip to content

Instantly share code, notes, and snippets.

@pwm
Created May 10, 2017 19:56
Show Gist options
  • Save pwm/3014800b91f5aa6bc23afdedcb36cefc to your computer and use it in GitHub Desktop.
Save pwm/3014800b91f5aa6bc23afdedcb36cefc to your computer and use it in GitHub Desktop.
Lifting out computation from iteration
<?php
declare(strict_types=1);
function uppercaseWordsImperative(array $words): void {
foreach ($words as $word) {
$word = strtoupper($word);
echo $word.' ';
}
}
uppercaseWordsImperative(['foo', 'bar', 'baz']);
echo PHP_EOL;
// [String] -> [String]
function uppercaseWords(array $words): Generator {
foreach ($words as $word) {
yield strtoupper($word);
}
}
// [String] -> IO ()
function uppercaseWordsImperativeShell(array $words): void {
foreach (uppercaseWords($words) as $word) {
echo $word.' ';
}
}
uppercaseWordsImperativeShell(['foo', 'bar', 'baz']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment