Created
January 26, 2013 22:40
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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