P16: a blog by Matt Kangas home archive
16 Jan 2008

Learning Erlang - Matrix iteration

I've added more examples to my Erlang "how to count" demo:


You'd think 10 examples of "counting to ten" would get pretty boring. But there's a surprising variety of options available. I'm a now big fan of "lists:foldl()" – it applies a function and lets you pass state between iteration steps. Most types of 1-D iteration can be done easily using "foldl()", without recursion. Don't overlook this function!

After figuring out list iteration, the next logical question is... how can I traverse a matrix? In C-style languages, you use a doubly-nested "for()" loop. Perhaps you may unroll the loop if you have special logic for the first/last elements, etc.

The prospect of writing doubly-nested recursive functions seemed downright nasty. But after a night's rest, I realized I wasn't constrained by C's one-dimensional "for()" anymore. I can write a single recursive function that traverses both axes of the matrix.

At that moment, I started to understand why functional guys always talk about "making their own control abstractions" (Armstrong, pp46). Who cares? Now I do, and it's not very hard.

Check out my count_matrix4() example. It's pretty clean, I think. Can we do better?