Skip to content

Instantly share code, notes, and snippets.

@quephird
Created January 26, 2013 22:40
Show Gist options
  • Save quephird/4645125 to your computer and use it in GitHub Desktop.
Save quephird/4645125 to your computer and use it in GitHub Desktop.
Just seeing how painful it is to try to be functional in Java
class Painful {
public static void main(String[] args) {
int[] firstTenIntegers = {1,2,3,4,5,6,7,8,9,10};
Functional squareFunction = new Functional() {
public int apply(int x) {
return x*x;
}};
Functional cubeFunction = new Functional() {
public int apply(int x) {
return x*x*x;
}};
System.out.println("Sum of squares of first ten numbers is: " + sum(firstTenIntegers, squareFunction));
System.out.println("Sum of cubes of first ten numbers is: " + sum(firstTenIntegers, cubeFunction));
}
public static int sum(int[] list, Functional f) {
int answer=0;
for (int i=0; i<list.length; i++) {
answer+=f.apply(list[i]);
}
return answer;
}
}
interface Functional {
public int apply(int x) ;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment