[ANN] Squeak just got lazy'er. :)

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

[ANN] Squeak just got lazy'er. :)

J J-6
Hello all,

I just published LazyList on squeaksource.  It is basically an ordinary
collection, but with completely lazy semantics.  So you can create infinite
lists like:

years := LazyElement enumerateFrom: 2006 with: [:year| year + interval ]

The list has many of the regular collection operations (well at least the
ones I needed. :), as well as some for dealing with the lazy nature (drop:
aNumber, dropWhile:, take: aNumber, takeWhile:).

All operations are completely lazy, so doing "aLazyList take: 500" just
returns something that knows how to take 500 from aLazyList.  To get the
list to actually evaluate use "asOrderedCollection" (it's easy to add more
"as" methods if needed).

The list implementation has basically two elements: an actual value (the
first value of the computation) and a function that knows how to generate
the next value, and the next generator function.  So this makes messages
like "allButFirst" fast since it is only required to compute one value.

So to give a quick usage example, imagine I had a list of dates I want to
show in a web page, but the dates are generated based on some computation
(recurrence rules for example) and are infinite in nature.  One might
implement the list display component like this:

PRBoxWidget subclass: #OccurrencesSelector
        instanceVariableNames: 'dateSource dateList'
        classVariableNames: ''
        poolDictionaries: ''
        category: 'web site'

OccurrencesSelector>>initialize

  dateSource := self datesStartingAt: DateAndTime now.    "The lazy list"
  dateList := OrderedCollection new.
  1 to: 10 do: [:n| self appendNextDate ]                          "Generate
initial list to display"

OccurrencesSelector>>appendNextDate
  dateList add: dateSource first.
  dateSource := dateSource allButFirst.     "This forces the next date to
evaluate"

OccurrencesSelector>>renderOn: html

  html someListDrawingMethodWith: dateList.
  html downArrowButton onClickDo: [ self appendNextDate ]


The caveat for this implementation is, of course, debugging.  The first
value is always calculated, but everything after that is buried in delayed
calculations and wont be run unless "asOrderedCollection" gets called, or a
select: gets ran that doesn't find anything.


I hope someone finds it useful.  Thanks,
Jason

_________________________________________________________________
Your Hotmail address already works to sign into Windows Live Messenger! Get
it now
http://clk.atdmt.com/MSN/go/msnnkwme0020000001msn/direct/01/?href=http://get.live.com/messenger/overview