Skip to content

Instantly share code, notes, and snippets.

@Danack
Created November 14, 2014 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Danack/bd96024c78cf2d0e1207 to your computer and use it in GitHub Desktop.
Save Danack/bd96024c78cf2d0e1207 to your computer and use it in GitHub Desktop.
FizzBuzz functional in PHP
<?php
$defaultCase = function ($x) {
return $x."\n";
};
$buzz = function ($x, callable $modify) {
if (($x%5) == 0) {
return "Buzz\n";
}
return $modify($x);
};
$fizz = function ($x, callable $modify) {
if (($x%3) == 0) {
return "Fizz\n";
}
return $modify($x);
};
$fizzbuzz = function ($x, callable $modify) {
if (($x%3) == 0) {
if (($x%5) == 0) {
return "FizzBuzz\n";
}
}
return $modify($x);
};
$callable = function ($x) use ($fizzbuzz, $fizz, $buzz, $defaultCase) {
$buzzCallable = function ($x) use ($buzz, $defaultCase) {
return $buzz($x, $defaultCase);
};
$fizzCallable = function ($x) use ($fizz, $buzzCallable) {
return $fizz($x, $buzzCallable);
};
return $fizzbuzz($x, $fizzCallable);
};
for($x=1 ; $x<40 ; $x++) {
echo $callable($x);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment