I have - rather lazily - constructed a chessboard like this:
board :=
With[
{
a = Flatten @ Table[{1, 1, 0, 0}, {4}],
b = Flatten @ Table[{0, 0, 1, 1}, {4}]
},
{a, a, b, b, a, a, b, b, a, a, b, b, a, a, b, b}
]
board // MatrixForm

letters =
Transpose[{Range@15, Style[#, Bold, 16] & /@
{"a", "", "b", "", "c", "", "d", "", "e", "", "f", "", "g", "", "h"}, Table[{0, 0}, {15}]}];
numbers =
Transpose[{Range@15, Style[#, Bold, 16] & /@
{"8", "", "7", "", "6", "", "5", "", "4", "", "3", "", "2", "", "1"}, Table[{0, 0}, {15}]}];
MatrixPlot[
board,
ColorFunction -> "Monochrome",
ImageSize -> 400,
Mesh -> {{0, 16}, {0, 16}},
PlotLabel -> Style["Chessboard\n", 16, Bold],
FrameTicks -> {{False , numbers}, {letters , False}}]

(a) How could "board" be written in a functional style?
(b) How could such a functional solution be extended to include other boards (like a 10*10 draughtsboard or an odd 11*11 board)?
Clarification
In Mathematica it's not always easy to distinguish functional and "other" styles of programming because the language incorporates many imperative constructs such as Do, Table, Array etc. For the purposes of this question, reliance of such imperative constructs should be avoided to make the answer correspond to a more functional programming paradigm, and thereby to distinguish it from the closely related question How to make a resizable chess board?.
A particular feature of the functional approach is that loops are replaced by recursions.
Answer
At least internally, the following is a nice recursive way of thinking about the chess board:
MatrixPlot[CellularAutomaton[250, {0, 1}, {7, 7}]]

Not sure if this is what was meant by functional style. It's hard to make a one-liner functional.
To address extensibility: the dimensions of the board are directly dictated by the argument {7,7}, and the repeating pattern of the board is a consequence of the rule 250 together with an initial condition that has isolated 1s alternating with 0s on the first row. The beauty of cellular automata is of course that they can generate patterns of all sorts of boards, you just have to find the right rule (and starting point). But this difficulty of finding the right initial condition is precisely the tradeoff that you incur when trying to generate a complex result in a functional way. So I think this captures the "philosophy" of functional programming.
Comments
Post a Comment