[Grace-core] Lists and filter

Andrew P Black black at cs.pdx.edu
Sun Aug 3 12:07:08 PDT 2014


On 1 Aug 2014, at 14:28 , Kim Bruce <kim at cs.pomona.edu> wrote:

> I'm a bit surprised that the method filter on a list returns an iterator.  I'm not planning on explaining iterators to my first course students (it's more appropriate for students in data structures).  That means I can't really teach my students about filter on lists.  Why not have filter on iterator return an iterator, but filter on lists return a list?
> 

Because of Phil Wadler's thesis!

The equivalent of filter (called select) in Smalltalk does return a reified collection.  So if you chain a number of map, filter, etc operations, you reify all of the intermediate data structures.  This is particularly bad if the end of the chain is a detect, which answers "true" on the first element.

The other problem, which can be worked around, is to decide what kind of collection to create.  When you filter a list, do you want another list, or a sequence, or a set?  You could, of course, always make a list, and then convert it, but that again introduces reified intermediate objects.   When you filter a set, do you want another set, or a sequence, or a list?  You could, of course, always make a set, but then you can't convert it to a sequence, because duplicates have already been eliminated.

Producing an iterator avoids all of this.  There are now convenient conversion methods on iterators, so you can say anIterator.asSet, anIterator.asList, etc.

Given that Grace's loops depends on iterators, I don't see how one can avoid them anyway.   Unless you use the do method consistently and don't talk about for and while.

To answer Marcos's question: why can't Iterators be a kind of List?  Their contents aren't mutable, for one thing.  And they maintain a state that is the "current element", which is advances whenever one says next.   So they don't support random access the way that lists do.   So, while it's reasonabvle to convert form one to the other, they don't have the same interface.

	Andrew

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mailhost.cecs.pdx.edu/pipermail/grace-core/attachments/20140803/d33721eb/attachment.html>


More information about the Grace-core mailing list