Rotating Squares

04 Jan 2017

Here’s a short one.

I use Colin Percival’s Hacker News Daily to catch the top ten articles
of the day on Hacker News. Today an article called Why Recursive Data
Structures? popped up, which illustrates that recursive algorithms can
become both intuitive and borderline trivial when a suitable data structure is
used to implement them. This is exactly the motivation for using recursion
schemes.

In the above article, Reginald rotates squares by representing them via a
quadtree. If we have a square of bits, something like:

.x..
..x.
xxx.
....

then we want to be able to easily rotate it 90 degrees clockwise, for example.
So let’s define a quadtree in Haskell:

Notice that you just have to shift each field of ‘NodeF’ rightward, with
wraparound. Then if you rotate and render the original tree you get:

.x..
.x.x
.xx.
....

Rotating things more times yields predictable results.

If you want to rotate another structure - say, a flat list - you can go through
a quadtree as an intermediate representation using the same pattern I described
in Sorting with Style. Build yourself a coalgebra and algebra pair: