Help wanted: Converting closure-based iterators into plain loops

Smalltalk, Ruby, Groovy and other languages allow one to implement loops using closures. But so does TextUML/UML. Given the primary use case of TextUML/UML is to generate code, one thorny question is how to generate code from a UML model using closures for implementing loops through collections into a language, like Java or C, just as one would normally write loops over collections in those closure-free languages.

Here are some examples of how to translate from closure-based loops (in TextUML, but the specific syntax shouldn’t matter) to ordinary loops (in Java, but again, syntax specifics shouldn’t matter):

forEach

In TextUML


self->units.forEach((u : Unit) { 
    link ProjectUnits(project := clone, units := u.clone()) }
);


In Java


for (Unit u : this.getUnits()) { 
    clone.addUnits(u.clone());
}

select

In TextUML


return Project extent.select((p : Project) : Boolean { return p.shared });

In Java


Set<Project> result = new HashSet<Project>();
for (Project p : Project.allInstances()) { 
    if (p.isShared()) {
        result.add(p);
    }
} 
return result;

collect

In TextUML


return Project extent.collect((p : Project) : User { return p->owner });

In Java


Set<User> result = new HashSet<User>();
for (Project p : Project.allInstances()) { 
    User owner = p.getOwner();
    result.add(owner);
} 
return result;

count

In TextUML


return Project extent.count((p : Project) : Boolean { return p.shared });

In Java


int count = 0;
for (Project p : Project.allInstances()) { 
    if (p.isShared()) {
        count++;
    }
} 
return count;

In AlphaSimple, we got much of what is needed above in place. There are though some additional challenges posed by the need of chaining those collection primitives, and the need for mapping the data flow that chains them together to an unchained form, using local variables in the target language. These last two aspects have been keeping me awake at night. If you feel like throwing a light (with strategies, references) on how to address that, by all means go for it, it is pretty dark in here right now… :)

EmailFacebookLinkedInGoogle+Twitter

2 thoughts on “Help wanted: Converting closure-based iterators into plain loops

  1. rafael.chaves

    May 15, 2011 at 10:42pm

    Thanks for mentioning lambdaj, Bernhard, very interesting, if for a different reason: I want to support similar operations in TextUML, so lambdaj is a good source of inspiration.

    But I wiil still need to be able to generate ordinary iteration code based on for/ifs, i.e. the generated code should run on standard Java without 3rd-party libraries.

Comments are closed.