Saturday, September 19, 2009

FizzBuzz Functional

{

I’ve been reading Tomas Petricek and John Skeet’s Functional Programming for the Real World. I’m hoping I can, as Steve McConnel says, program into1 my C# projects some elements of functional problem solving. As I was working to grok the beginning portions of the book I thought I’d rewrite FizzBuzz since I’ve aleady posted a few versions of a solution. Here is my solution:

Func<int, int[], bool> isMultiple = (n, n2) => n2.Any(m => n % m == 0);
Func<int, int, string, string> fb = (n, n2, s) => (n % n2 == 0) ? s : String.Empty;


foreach(var i in Enumerable
.Range(1, 100)
.Select(n =>(isMultiple(n, new int[]{3,5}))
?fb(n, 3, "Fizz") + fb(n, 5, "Buzz")
:fb(n, n, n.ToString())
)Console.WriteLine(i);


Another version, using ForEach on a List<T>:



Func<int, int[], bool> isMultiple = (n, n2) => n2.Any(m => n % m == 0);
Func<int, int, string, string> fb = (n, n2, s) => (n % n2 == 0) ? s : String.Empty;

Enumerable
.Range(1, 100)
.Select(n => (isMultiple(n, new int[] { 3, 5 }))
? fb(n, 3, "Fizz") + fb(n, 5, "Buzz")
: fb(n, n, n.ToString()))
.ToList()
.ForEach(num => Console.WriteLine(num));


I'm just starting to wade into using F# but I'm hoping to start building my proficiency the further I get into the book



1"Don't limit your programming thinking only to the concepts that are supported automatically by your language. The best programmers think of what they want to do, and then they assess how to accomplish their objectives with the programming tools at their disposal." – Steve McConnell, Code Complete 2nd Edition



}

No comments: