s c h e m a t i c s : c o o k b o o k

/ Cookbook.ListCircularList

This Web


WebHome 
WebChanges 
TOC (with recipes)
NewRecipe 
WebTopicList 
WebStatistics 

Other Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Schematics


Schematics Home
Sourceforge Page
SchemeWiki.org
Original Cookbook
RSS

Scheme Links


Schemers.org
Scheme FAQ
R5RS
SRFIs
Scheme Cross Reference
PLT Scheme SISC
Scheme48 SCM
MIT Scheme scsh
JScheme Kawa
Chicken Guile
Bigloo Tiny
Gambit LispMe
GaucheChez

Lambda the Ultimate
TWiki.org

Building a Circular List

Problem

You want to build a list that's circular; that is, as you navigate it, you eventually reach the head again. For example, ring buffers can be implemented with circular lists.

Solution

If you set-cdr! on the last-pair of a list to the list, you have a circular list:
> (define rb '(1 2 3 4))
> (set-cdr! (last-pair rb) rb)
> rb
#0=(1 2 3 4 . #0#)

Note the odd notation the #0= at the start and the . #0# on the tail is telling you the list is circular. Look at what the result of cdr is:

> (cdr rb)
#0=(2 3 4 1 . #0#)

Discussion

Circular lists do require care when you're working with list functions, many functions will not accept a circular list, or will not terminate when given one. The problem is in detecting the head of the list; if list elements aren't unique, you can't simply check if you've seen an element before. In the ring buffer case, you probably have a fixed size ring buffer, so it's easiest just to keep track of how many elements you've seen when traversing a list and comparing to the known length.

SRFI-1 also has functions circular-list for building circular lists and circular-list? for determining if a list is circular.

> (circular-list 1 2 3 4)
#0=(1 2 3 4 . #0#)


Comments about this recipe

Contributors

-- GordonWeakliem - 12 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: ListRecipes
TopicOrder: 999

 
 
Copyright © 2004 by the contributing authors. All material on the Schematics Cookbook web site is the property of the contributing authors.
The copyright for certain compilations of material taken from this website is held by the SchematicsEditorsGroup - see ContributorAgreement & LGPL.
Other than such compilations, this material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest