diff --git a/Lab6/cs2030s/fp/Lazy.java b/Lab6/cs2030s/fp/Lazy.java index 55101e5..13743ab 100644 --- a/Lab6/cs2030s/fp/Lazy.java +++ b/Lab6/cs2030s/fp/Lazy.java @@ -1,5 +1,41 @@ package cs2030s.fp; -public class Lazy /* implements Immutatorable */ { +public class Lazy implements Immutatorable { private Constant init; -} \ No newline at end of file + + protected Lazy(Constant c) { + this.init = c; + } + + public T get() { + return init.init(); + } + + public static Lazy from(T v) { + return new Lazy<>(() -> v); + } + + public static Lazy from(Constant v) { + return new Lazy(v); + } + + @Override + public Lazy transform(Immutator f) { + return Lazy.from(() -> f.invoke(this.init.init())); + } + + public Lazy next(Immutator, ? super T> f) { + + @SuppressWarnings("unchecked") + Lazy result = (Lazy) Lazy.from(() -> f.invoke(this.init.init())); + + return result; + + } + + @Override + public String toString() { + return this.init.init().toString(); + } + +} diff --git a/Lab6/cs2030s/fp/Memo.java b/Lab6/cs2030s/fp/Memo.java index 9831dad..27a54a9 100644 --- a/Lab6/cs2030s/fp/Memo.java +++ b/Lab6/cs2030s/fp/Memo.java @@ -2,4 +2,43 @@ package cs2030s.fp; public class Memo extends Lazy { private Actually value; + + protected Memo(Constant c) { + super(c); + // if actually is err, it is uninitialised + this.value = Actually.err(null); + } + + protected Memo(T v) { + super(() -> v); + this.value = Actually.ok(v); + } + + public static Memo from(T v) { + return new Memo(v); + } + + public static Memo from(Constant v) { + return new Memo(v); + } + + public T get() { + T result = this.value.except(() -> super.get()); + this.value = Actually.ok(result); + return result; + } + + @Override + public Memo transform(Immutator f) { + return Memo.from(() -> f.invoke(this.get())); + } + + public Memo next(Immutator, ? super T> f) { + return Memo.from(() -> f.invoke(this.get()).get()); + } + + @Override + public String toString() { + return this.value.next(t -> Actually.ok(String.valueOf(t))).unless("?"); + } } \ No newline at end of file