Skip to content

Instantly share code, notes, and snippets.

@phagenlocher
Last active September 7, 2020 15:00
Show Gist options
  • Select an option

  • Save phagenlocher/5c8b03d6174ea77cfa4cee4b6bc633d3 to your computer and use it in GitHub Desktop.

Select an option

Save phagenlocher/5c8b03d6174ea77cfa4cee4b6bc633d3 to your computer and use it in GitHub Desktop.
Lazy Evaluation in Java (https://youtu.be/KniIeHiEzdo)
package main;
public interface Lazy<R> {
public R force();
}
package main;
public class Main {
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) {
Lazy a = new Singleton(1);
Lazy b = new Singleton(2);
Lazy c = new Thunk<Integer, Integer, Lazy<Integer>, Lazy<Integer>, Integer>((x,y) -> x+y, a, b);
Lazy d = new Thunk<Integer, Integer, Lazy<Integer>, Lazy<Integer>, Integer>((x,y) -> x+y, a, c);
System.out.println("c before force: " + c);
System.out.println("d before force: " + d);
d.force();
System.out.println("c after force: " + c);
System.out.println("d after force: " + d);
}
}
package main;
public class Singleton<V> implements Lazy<V> {
private V value;
public Singleton(V value) {
this.value = value;
}
@Override
public V force() {
return value;
}
}
package main;
import java.util.function.BiFunction;
public class Thunk<A1, A2, LA1 extends Lazy<A1>, LA2 extends Lazy<A2>, R> implements Lazy<R> {
private BiFunction<A1,A2,R> fun;
private LA1 arg1;
private LA2 arg2;
private R result;
public Thunk(BiFunction<A1,A2,R> fun, LA1 arg1, LA2 arg2) {
this.fun = fun;
this.arg1 = arg1;
this.arg2 = arg2;
this.result = null;
}
@Override
public R force() {
if(result == null)
result = fun.apply(arg1.force(), arg2.force());
return result;
}
public String toString() {
String valString = result == null ? "_" : result.toString();
return "Lazy(" + valString + ")";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment