TABA pattern in Haskell June 6, 2009

After a recent discussion on Haskell-Cafe I read over the excellent paper entitled There and Back Again (TABA) by Danvy and Goldberg and was quite fascinated.

So what is TABA? In a nutshell, the TABA pattern utilizes a recursive function to traverse a data structure such as a list at return time. This allows one to, e.g., convolve two list [x1, x2, …, xn] and [y1, y2, …, yn] to yield

[(x1,yn), (x2,yn-1), …, (xn,y1)]

in only n recursive calls.

So how does this work? The main idea is that during the recursive traversal of the first list we build up a stack of functions each of which is responsible for generating one of the final list elements. During stack unwinding these function are being replayed and generate the final result. The authors of the TABA paper liken it to winding a spring during the recursive traversal. If this sounds a bit too abstract here’s a Haskell implementation of a list convolution function using the TABA pattern