Hi,
I'm looking at the signature for something like a 'map' function.
For List it may be something like:
List<B> map(List<A> a, UnaryFunction<A, B> f)
But, I want I'd rather it not be List specific, so I was after
something like:
T<B> map(T<A> a UnaryFunction<A, B> f)
But, the compiler doesn't like this
Any ideas on how or whether this is possible?
I've implemented a functional library that addresses this issue. I
just use the Iterable<T> type unless the operation specifically
depends on list ordering. Here's a skeleton of my class declarations
adapted to your notation. Note, my implementation uses lazy
evaluation so you can do things like sum up an infinite list.
For example, I can create a Range class that takes a starting and
finishing value and implements Iterable<Integer>. I can write code
like this:
Range r = new Range(0, Integer.MAX_VALUE);
UnaryFunction sqr = new Square();
Iterable<Integer> squares = map( sqr, r );
for ( Integer x : squares )
{
// do something
if ( x > 100 )
break;
}
Here is the code outline:
public class UnaryFunction<R, T> {
public R eval( T arg ) { ... }
}
public static <R, T> Iterable<R> map( final UnaryFunction<R, T> f,
final Iterable<? extends T> list )
{
return new Iterable<R>() {
public Iterator<R> iterator() {
return map_iterator( f, list.iterator() );
}
}
}
private static <R, T> Iterator<R> map_iterator( final UnaryFunction<R,
T> f, final Iterator<? extends T> iterator )
{
return new Iterator<R>()
{
public boolean hasNext() {
return list.hasNext();
}
public R next() {
return f.eval( list.next() );
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}