Example functional programming fold left and fold right in java 본문

Programming/Java

Example functional programming fold left and fold right in java

halatha 2011. 4. 30. 04:28
import java.util.ArrayList;
import java.util.List;

//	http://abel-perez.com/example-functional-programming-fold-left-and
public class TestFunctionalSum	{
	public static int foldLeft(List<Integer> elements,
		int seed,
		Function<Integer, Integer> function)	{
		int	accumulated	=	seed;
		for ( final Integer element : elements )	{
			accumulated	=	function.apply(element, accumulated);
		}
		return	accumulated;
	}

	public static void main(final String[] args)	{
		final List<Integer>	elements	=	new ArrayList<Integer>();
		elements.add(2);
		elements.add(6);
		elements.add(10);
		elements.add(5);
		elements.add(2);

		final int	result	=
			foldLeft(elements, 0, new Function<Integer, Integer>() {
				public Integer apply(Integer x, Integer y) {
					return	x + y;
				}
			});
		System.out.println(result);
	}
}

interface Function<A, B>	{
	public B apply(A element, B accumulated);
}
Comments