Skip to content

Instantly share code, notes, and snippets.

@banterCZ
Last active August 29, 2015 14:02
Show Gist options
  • Save banterCZ/a41a27a496ae792a21ea to your computer and use it in GitHub Desktop.
Save banterCZ/a41a27a496ae792a21ea to your computer and use it in GitHub Desktop.
We want to write a function that generates accumulators-- a function that takes a number n, and returns a function that takes another number i and returns n incremented by i. See the article Revenge of the Nerds http://www.paulgraham.com/icad.html
def foo(n) {
return {n += it}
}
def accumulator = foo(1)
assert accumulator(2) == 3
assert accumulator(3) == 6
public class Accumulator {
public interface Inttoint {
public int call(int i);
}
public static Inttoint foo(final int n) {
return new Inttoint() {
int s = n;
public int call(int i) {
s = s + i;
return s;
}};
}
public static void main(String... args) {
Inttoint accumulator = foo(1);
System.out.println(accumulator.call(2) == 3);
System.out.println(accumulator.call(3) == 6);
}
}
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
public class Accumulator8 {
public static Function<Integer,Integer> foo(int n) {
return new AtomicInteger(n)::addAndGet;
}
public static void main(String... args) {
Function<Integer, Integer> accumulator = foo(1);
System.out.println(accumulator.apply(2) == 3);
System.out.println(accumulator.apply(3) == 6);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment