#223 Enumerable mixin

mike Tue 6 May 2008

If I'm writing a script, I'm much more of a Python person than a Ruby person. Having said that, one thing that Ruby has that is really wonderful is the Enumerable mixin. I think Fan should have that as well.

All one has to do with Enumerable is implement each, and some version of the <=> spaceship operator (like java.lang.Comparable, which fan also seems to be lacking). Enumerable would be very useful in cases (such as iterating through database records) where List's random access interface doesn't make sense.

Notes:

  • About half of the interface in sys::List simply implements the Enumerable functionality. This could all be moved up into sys::Enumerable.
  • sys::List.each is kind of like Ruby's each_with_index. Maybe sys::Enumerable needs to draw a distinction between each and eachWithIndex. Not sure about that.

brian Tue 6 May 2008

I've considered something like Enumerable, but the main problem is that it doesn't work well with List as a generic.

I'm also not sure it would all be that useful in Fan. For example the compiler does all the work to implement all the various comparison operators via Obj.compare - so we don't need a type for that.

And iteration should really just any function like |Obj x| - using function types is a lot more flexible than class/mixin types. For example whether you have a Int index or not can just be another parameter that might or might not be used. For instance a function of |Obj x| can already be used to iterate a List, Map, or a sql query.

mike Thu 8 May 2008

I do think that making a sql query resultset be a List is a mistake though. Its really a bad idea to fetch all the results from a query automatically -- that should be under the control of the application programmer. There could be millions of rows coming back, and their may be no good reason to cache them all in the heap before they can be analyzed by the applictation. A convenience method that puts the rows into a List is a far better approach IMHO.

andy Thu 8 May 2008

We talked about it - but Fan is about the common case to make your life easier. In my experience, you end up fetching the entire result set, so don't make me complicate my code by doing it manually. However, you do need to handle your case, so we need to support both mechanisms.

brian Thu 8 May 2008

It already works both ways, so that is a non-issue:

  • Statement.query returns a list
  • Statement.queryEach takes a function and iterates

mike Thu 8 May 2008

Statement.queryEach is exactly what I was looking for. Objection withdrawn.

Login or Signup to reply.