Skip to content
This repository has been archived by the owner on Jan 30, 2024. It is now read-only.

Commit

Permalink
Memoize tail
Browse files Browse the repository at this point in the history
Change the tail evaluation so that the closure is called only once.
  • Loading branch information
yloiseau authored and Julien Ponge committed Jun 25, 2015
1 parent 413a902 commit beb08bb
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
1 change: 1 addition & 0 deletions src/main/golo/lazylist.golo
Expand Up @@ -52,6 +52,7 @@ local function head = |l| -> l: head()
local function tail = |l| -> l: tail()
local function isEmpty = |l| -> l: isEmpty()

# TODO: rename emptyList() ?
----
Returns the empty list.
----
Expand Down
24 changes: 17 additions & 7 deletions src/main/java/gololang/LazyList.java
Expand Up @@ -27,6 +27,12 @@
* <p>
* A lazy list behaves like a linked list, but each next element
* is represented by a closure that is evaluated only if needed.
* The value is memoized, so that the closure representing the tail
* is evaluated only once.
*
* Since the tail closure will be called at most once, and we can't
* guarantee when, or even if, it will be called, this closure must be
* a pure, side-effect free, function.
*/
public final class LazyList implements Collection<Object> {

Expand Down Expand Up @@ -65,8 +71,9 @@ public void remove() {
}
}

private Object head;
private MethodHandle tail;
private final Object head;
private final MethodHandle tail;
private LazyList memoTail = null;

/**
* Create a new list from the head and tail values.
Expand Down Expand Up @@ -95,11 +102,14 @@ public Object head() {
* contains only one value, or if the closure failed.
*/
public LazyList tail() {
try {
return (LazyList) (this.tail.invokeWithArguments());
} catch (Throwable e) {
return EMPTY;
if (memoTail == null) {
try {
memoTail = (LazyList) (this.tail.invokeWithArguments());
} catch (Throwable e) {
memoTail = EMPTY;
}
}
return memoTail;
}

/**
Expand Down Expand Up @@ -133,7 +143,7 @@ public Iterator<Object> iterator() {
* @return a new {@code LinkedList}
*/
public List<Object> asList() {
List<Object> lst = new LinkedList();
List<Object> lst = new LinkedList<>();
for (Object o : this) {
lst.add(o);
}
Expand Down

0 comments on commit beb08bb

Please sign in to comment.