PROPOSAL: fold keyword

Tim Peierls tim at peierls.net
Thu Mar 5 14:24:13 PST 2009


Also check out ParallelArray, which is built on top of the ForkJoin
framework proposed for Java 7:
http://gee.cs.oswego.edu/dl/jsr166/dist/extra166ydocs/extra166y/ParallelArray.html

The simple example becomes trivial:

    long sum = parallelLongArray.sum();

The more complex example that Josh mentioned would look like this:

   ParallelArray<Employee> emps = ...

   // Salaries of employees not on vacation:
   return emps
       .withFilter(notPredicate(isOnVacation))
       .withMapping(salaryField)
       .all();

where notPredicate is a static import from CommonOps, and isOnVacation and
salaryField could be defined as:

   static final Predicate<Employee> isOnVacation = new Predicate<Employee> {
       public boolean op(Employee e) { return e.onVacation(); }
   };

   static final Op<Employee, BigDecimal> salaryField = new Op<Employee,
BigDecimal> {
       public BigDecimal op(Employee e) { return e.getSalary(); }
   };

These examples are likely to outperform the sequential versions on a
multiprocessor for moderately large inputs.

--tim

On Thu, Mar 5, 2009 at 4:28 PM, Joshua Bloch <jjb at google.com> wrote:

> Gabriel,
>
> This doesn't seem compelling.
>
> Here's your simple example:
>
>    // sum all numbers in the list
>    Integer sum =
>    fold(Integer n : list;     // iterating collection element n
>         Integer result = 0) { // Where to accumulate the result, and
>             the initial value
>             result += n;
>         };
>    }
>
> And here's how it looks today (with no change to the language or
> libraries):
>
>    Integer sum = 0;
>    for (Integer n : list)
>        sum += n;
>
>
> Here's one of your complex examples:
>
>  // returns a new collection with the salaries of the employees not on
> vacation
>  List<BigDecimal> salaries =
>   fold(Employee e : emps;
>        List<BigDecimal> newList = new ArrayList<BigDecimal>()) {
>     if (!e.onVacation()) {
>       newList.add(e.getSalary());
>     }
>   }
>
> And here's how it looks today:
>
>     List<BigDecimal> salaries = new ArrayList<BigDecimal>();
>     for (Employee e : emps)
>         if (!e.onVacation())
>             salaries.add(e.getSalary());
>
> To my eyes, the current version is clearer as well as shorter.
>
>            Josh
>
>



More information about the coin-dev mailing list