Created
October 10, 2013 03:27
-
-
Save aybabtme/6912599 to your computer and use it in GitHub Desktop.
Pseudo functional programming in Java
This file contains 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
public class Main { | |
// Pseudo lambda | |
public interface Operation { | |
double apply(double arg); | |
} | |
// Takes in pseudo-lambda | |
public static double times(Operation toApply, int times) { | |
double result = 1.0; | |
for (int i = 0; i < times; i++) { | |
result = toApply.apply(result); | |
} | |
return result; | |
} | |
public static void main(String[] argv) { | |
// Java refuses to let you use non-final variables inside an anonymous type. | |
// so make it an array of size 1. | |
final double[] fact = {10.0}; | |
// Pseudo-closure over `fact` | |
Operation power = new Operation() { | |
@Override | |
public double apply(double arg) { | |
return fact[0] * arg; | |
} | |
}; | |
// Use lambda `power` with method `times(...)` | |
double result = times(power, 2); | |
System.out.printf("Answer = %f\n", result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment