On Sun, Oct 25, 2009 at 10:08 PM, John Harrop <jharrop...@gmail.com> wrote:
>
> 4  public class NodeCounter {
> 8      public static int countNodes (Object data) {
> 10         if (!(data instanceof Iterable)) return 1;
> 5          int result = 1;
> 8          for (Object e : (Iterable)data) {
> 6              result += countNodes(e);
> 0          }
> 3          return result;
> 0      }
> 0  }
> ------
> 44
>
> This is actually slightly better than the loop/recur version in Clojure,
> despite the types everywhere, probably because of the for-each loop being a
> bit more abstract than loop/recur (a while with an explicit iterator would
> perhaps be a fairer comparison; and map + reduce is clearly much more
> abstract still) and the use of recursion. It would surely blow up to 60 or
> even 70 if we added explicit stack management to traverse the tree
> non-recursively and used a while loop with an explicit iterator.
>

It's worse than I thought:

4  public class NodeCounter {
8      public static int countNodes (Object data) {
7          LinkedList stack = new LinkedList();
6          stack.add(data);
5          int result = 1;
9          while (!(stack.isEmpty())) {
3              result++;
8              Object front = stack.getFirst();
6              if (front instanceof Iterable) {
10                 Iterator i = ((Iterable)front).iterator();
6                  while (i.hasNext())
9                      stack.addFirst(i.next());
0              }
0          }
3          return result;
0      }
0  }
----
84

This is the closest possible Java to the loop-recur implementation. It's
about 68% larger in complexity by the AST-size metric.

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to