Skip to content

Commit 0906174

Browse files
committed
List.append() was implemented ineffectively. Added Buffer.isEmpty(), Buffer.prependToList().
1 parent 81daa76 commit 0906174

File tree

1 file changed

+27
-5
lines changed

1 file changed

+27
-5
lines changed

core/src/main/java/fj/data/List.java

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -624,7 +624,7 @@ public final <B> List<B> apply(final List<F<A, B>> lf) {
624624
* @return A new list that has appended the given list.
625625
*/
626626
public final List<A> append(final List<A> as) {
627-
return fromList(this).append(as).toList();
627+
return Buffer.fromList(this).prependToList(as);
628628
}
629629

630630
/**
@@ -1787,7 +1787,7 @@ public Iterator<A> iterator() {
17871787
* Appends (snoc) the given element to this buffer to produce a new buffer.
17881788
*
17891789
* @param a The element to append to this buffer.
1790-
* @return A new buffer with the given element appended.
1790+
* @return This buffer.
17911791
*/
17921792
public Buffer<A> snoc(final A a) {
17931793
if (exported)
@@ -1806,10 +1806,10 @@ public Buffer<A> snoc(final A a) {
18061806
}
18071807

18081808
/**
1809-
* Appends the given buffer to this buffer.
1809+
* Appends the given list to this buffer.
18101810
*
1811-
* @param as The buffer to append to this one.
1812-
* @return A new buffer that has appended the given buffer.
1811+
* @param as The list to append to this buffer.
1812+
* @return This buffer.
18131813
*/
18141814
public Buffer<A> append(final List<A> as) {
18151815
for (List<A> xs = as; xs.isNotEmpty(); xs = xs.tail())
@@ -1818,6 +1818,28 @@ public Buffer<A> append(final List<A> as) {
18181818
return this;
18191819
}
18201820

1821+
/**
1822+
* Prepends the elements of this buffer to the given list.
1823+
*
1824+
* @param as the list to which elements are prepended.
1825+
*/
1826+
public List<A> prependToList(final List<A> as) {
1827+
if (isEmpty()) {
1828+
return as;
1829+
} else {
1830+
if (exported)
1831+
copy();
1832+
1833+
tail.tail(as);
1834+
return toList();
1835+
}
1836+
}
1837+
1838+
/**
1839+
* Returns <code>true</code> if this buffer is empty, <code>false</code> otherwise.
1840+
*/
1841+
public boolean isEmpty() { return start.isEmpty(); }
1842+
18211843
/**
18221844
* Returns an immutable list projection of this buffer. Modifications to the underlying buffer
18231845
* will <em>not</em> be reflected in returned lists.

0 commit comments

Comments
 (0)