[Haskell-beginners] Circular Linked Lists

Dave Bayer bayer at cpw.math.columbia.edu
Tue Feb 3 08:56:34 EST 2009

On Feb 2, 2009, at 9:45 PM, Matthew J. Williams wrote:

> Dear All
> How would one mimic, in Haskell, a C++ circular linked list i.e.,  
> where the last element precedes (points to) the first?

You are getting deep answers to what is perhaps a simple question. You  
haven't said exactly what you want to do with a circular linked list,  
and people are perhaps fearing the trickiest applications.

Have you tried the Prelude function cycle?

> cycle :: [a] -> [a]
> cycle ties a finite list into a circular one, or equivalently, the  
> infinite repetition of the original list. It is the identity on  
> infinite lists.

For instance, in ghci one gets

> Prelude> [1..3]
> [1,2,3]
> Prelude> take 10 $ cycle [1..3]
> [1,2,3,1,2,3,1,2,3,1]

cycle doesn't actually construct in memory a cyclic data structure, as  
one might in C. It's more like those repeat bars in sheet music.

More information about the Beginners mailing list