#1154 Feature: List methods

jodastephen Tue 20 Jul 2010

One simple programming example is how to add all the elements in a list. Does Fantom have a method for that? Best I could find was:

list := [1, 4, 7, 8]
total := list.reduce(0) |r, v| { v + r }

While this is fine, I don't consider it ideal, so I thought I'd write up this more broad proposal.

Aim

Methods on lists specific to the content type of the list. For example:

list := [1, 4, 7, 8]
total := list.sum()

A new method sum() applicable only to Int[].

Rationale

Sometimes you need a method that acts on the whole list. While closures each/map/reduce provide much power, they require the developer to write the same code multiple times in multiple places. It is more efficient to write a "sum()" method once, test it and reuse it than write it many times. Plus, hotspot will prefer one implementation (and it results in smaller class sizes in general).

Possible syntax

class Int {
  // other int methods

  class Int[] {
    Int sum() {
      reduce(0) |r, v| { v + r }
    }
  }
}

The additional definition introduced by class Type[] defines methods to be available on the list of Int. Within the declaration, the scope is that of the list.

Implementation

Probably via a static helper class:

intList.sum();
// effectively translated to
Int$List.sum(intList)

Summary

While this example is very simple, the ability to add methods to a list is something I found incredibly useful. (In the past I had a system of code generated List subclasses, like PersonList, where these dedicated methods could sit).

This could be added post-1.0, but it would be a cool feature to do sooner.

DanielFath Tue 20 Jul 2010

Yeah static helper methods would be awesome. I however fail to realize why sum() would be only limited to Int? The use case seems obvious, anything that extends Num and has a plus method should be a viable. But this leads us to a problem of the missing generics...

brian Tue 20 Jul 2010

Yeah, something like that would be cool. It seems right inline with C# extension methods which is how I've been thinking we should do stuff like this.

jodastephen Tue 20 Jul 2010

Just to note that in theory, the same concept should apply to maps, but the problems are a lot trickier.

BTW, I agree that sum() could apply to every subclass of Num. The proposal keeps it simple for now.

keilw Thu 22 Jul 2010

Some of the suggestions sound interesting. If those related to Num were pursued, then I suggest looking at Unit and its conversions dealing with Num rather than concrete subclasses like Float. This way the precision problem or multiple Measure classes could be avoided.

Many Java implementations like ICU4J or the Units of Measure API try to stick with Number instead of forcing concrete subclasses like BigDecimal onto people.

DanielFath Thu 22 Jul 2010

But assuming Num is extensible, what happens if I add complex numbers. Can any unit be measured in Complex numbers?

Login or Signup to reply.