M
Morton Goldberg
After completing my Ruby Quiz submission, I decided to implement
FizzBuzz in Mathematica. Here is the first version that I wrote.
f[x_] := Print["FizzBuzz"] /; Mod[x, 15] == 0
f[x_] := Print["Buzz"] /; Mod[x, 5] == 0
f[x_] := Print["Fizz"] /; Mod[x, 3] == 0
f[x_] := Print[x]
f /@ Range[100];
I think this example pretty well gives the flavor of Mathematica.
Note that no explicit flow control is needed. Of course, Mathematica,
like Ruby, allows one to write FizzBuzz in many ways, including some
that would look much more procedural and others that are more
functional. Here is an example of the latter.
MapThread[(f[z_] := Print[#1] /; Mod[z, #2] == 0) &,
{{"FizzBuzz", "Buzz", "Fizz"}, {15, 5, 3}}];
f[x_] := Print[x]
f /@ Range[100];
In this second example, the MapThread generates three lines of code
equivalent to the first three lines of the first example.
I apologize to anyone who finds this off topic post distracting, but
I am hoping at least some readers of mailing list will find it
interesting to see FizzBuzz in a language very different both from
Ruby and all the well-known static, procedural languages.
Regards, Morton
FizzBuzz in Mathematica. Here is the first version that I wrote.
f[x_] := Print["FizzBuzz"] /; Mod[x, 15] == 0
f[x_] := Print["Buzz"] /; Mod[x, 5] == 0
f[x_] := Print["Fizz"] /; Mod[x, 3] == 0
f[x_] := Print[x]
f /@ Range[100];
I think this example pretty well gives the flavor of Mathematica.
Note that no explicit flow control is needed. Of course, Mathematica,
like Ruby, allows one to write FizzBuzz in many ways, including some
that would look much more procedural and others that are more
functional. Here is an example of the latter.
MapThread[(f[z_] := Print[#1] /; Mod[z, #2] == 0) &,
{{"FizzBuzz", "Buzz", "Fizz"}, {15, 5, 3}}];
f[x_] := Print[x]
f /@ Range[100];
In this second example, the MapThread generates three lines of code
equivalent to the first three lines of the first example.
I apologize to anyone who finds this off topic post distracting, but
I am hoping at least some readers of mailing list will find it
interesting to see FizzBuzz in a language very different both from
Ruby and all the well-known static, procedural languages.
Regards, Morton