Created
April 22, 2012 20:32
-
-
Save alexandream/2466704 to your computer and use it in GitHub Desktop.
Print 1 to 100 without loops or conditionals
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 Lambdas | |
{ | |
public static void main(String args[]) { | |
Printer p = new Printer(); | |
times10(times10(p)).call(); | |
} | |
// The "add" function returns the function that executes the parameters f and g | |
// one after the other. | |
// | |
// The "timesN" functions return objects that call() their parameter N | |
// times in sequence when call()ed. | |
public static ICallable add(ICallable f, ICallable g) { | |
return new Plus(f, g); | |
} | |
public static ICallable times2(ICallable f) { | |
return add(f, f); | |
} | |
public static ICallable times5(ICallable f) { | |
return add(f, times2(times2(f))); | |
} | |
public static ICallable times10(ICallable f) { | |
return times2(times5(f)); | |
} | |
} | |
interface ICallable { | |
void call(); | |
} | |
// This creates an object that will print n and increment it whenever | |
// it's call()ed. | |
class Printer implements ICallable { | |
private int n; | |
public Printer() { | |
n = 1; | |
} | |
public void call() { | |
System.out.printf("%1$d\n", n++); | |
} | |
} | |
class Plus implements ICallable { | |
private ICallable f; | |
private ICallable g; | |
public Plus(ICallable f, ICallable g) { | |
this.f = f; | |
this.g = g; | |
} | |
public void call() { | |
this.f.call(); | |
this.g.call(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment