Last active
August 29, 2015 14:02
-
-
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
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
def foo(n) { | |
return {n += it} | |
} | |
def accumulator = foo(1) | |
assert accumulator(2) == 3 | |
assert accumulator(3) == 6 |
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 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); | |
} | |
} |
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
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