Gang,

I was thinking an hour ago; How about doing the following in Qi4j?

    java.util.List<Integer> integers = module.newTransient( List.class );

    // populate list

    FList<Integer> list = (FList<Integer>) integers;

    java.util.List<String> strings = list.translate( Function( Integer
x ) { return x.toString(); } );


Ok. Agree that the last line is a bit "too much", but that is how IDEA
renders the following actual code;

        List<String> strings = list.translate( new Function<Integer, String>()
        {
            @Override
            public String map( Integer x )
            {
                return x.toString();
            }
        } );

But that is not the point. How do I get this to work at all??


It was a lot simpler than I expected. First we need the FList
interface, i.e. a List we can pass function (Function here is from
org.qi4j.functional) in a translate method.

    @Mixins( FListMixin.class )
    public interface FList<FROM>
    {
        <TO> List<TO> f( Function<FROM, TO> function );
    }

And a very simple implementation, which just loop the values, which is
obtained via the @This pointer back to the composite itself.

    public class FListMixin<FROM>
        implements FList<FROM>
    {
        @This
        private List<FROM> list;

        @Override
        public <TO> List<TO> f( Function<FROM, TO> function )
        {
            ArrayList<TO> result = new ArrayList<TO>();
            for( FROM data : list )
            {
                result.add( function.map( data ) );
            }
            return result;
        }
    }


Finally, the assembly for all of this is what makes it look all sweet;

    @Override
    public void assemble( ModuleAssembly module )
        throws AssemblyException
    {
        module.transients( List.class ).withTypes( FList.class
).withMixins( ArrayList.class );
    }


I don't know about you guys, but this looks fairly sweet to me... All
with regular features in Qi4j now.

We could build up a full library of functional style Java Util
Collection classes with very little effort. Not sure that we should
spend the time on that right now, but low hanging fruits for somehow
who want to get their feet wet.



Cheers
--
Niclas Hedhman, Software Developer
http://www.qi4j.org - New Energy for Java

I live here; http://tinyurl.com/3xugrbk
I work here; http://tinyurl.com/6a2pl4j
I relax here; http://tinyurl.com/2cgsug

_______________________________________________
qi4j-dev mailing list
[email protected]
http://lists.ops4j.org/mailman/listinfo/qi4j-dev

Reply via email to