Skip to content

Instantly share code, notes, and snippets.

@didier-wenzek
Created September 22, 2014 17:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save didier-wenzek/07faa3990ff03fdea372 to your computer and use it in GitHub Desktop.
Save didier-wenzek/07faa3990ff03fdea372 to your computer and use it in GitHub Desktop.
Transducers in java
interface Fun<A,B> {
B apply(A a);
}
public class Mapping<A,B> implements Transducer<B,A>
{
final Fun<A,B> f;
public Mapping(Fun<A,B> f) { this.f = f; }
public <R> Reducer<A,R> transduce(final Reducer<B,R> reducer) {
return new Reducer<A,R>() {
public R init() { return reducer.init(); }
public R step(R acc, A item) { return reducer.step(acc, f.apply(item)); }
};
}
}
interface Reducable<A> {
<R> R reduce(Reducer<A,R> reducer);
}
interface Reducer<A,R> {
R init();
R step(R acc, A item);
}
public class Sum implements Reducer<Long,Long> {
public Long init() { return 0L; }
public Long step(Long acc, Long item) { return acc + item; }
}
public class Test {
public static void main(String args[]) {
Fun<String,Long> decode = new Fun<String,Long>() {
public Long apply(String s) { return Long.valueOf(s); }
};
Reducer<Long,Long> sum = new Sum();
Reducer<String,Long> process = new Mapping(decode).transduce(sum);
WordReader inputs = new WordReader();
Long result = inputs.reduce(process);
System.out.println("sum = " + result);
}
}
interface Transducer<A,B> {
<R> Reducer<B,R> transduce(Reducer<A,R> reducer);
}
import java.util.Scanner;
public class WordReader implements Reducable<String> {
public <R> R reduce(Reducer<String,R> reducer) {
R acc = reducer.init();
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
acc = reducer.step(acc, sc.next());
}
return acc;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment