Add a functional List type? #69
Replies: 3 comments 1 reply
-
This is an interesting idea! Coincidentally, I've run into a similar use case that may have benefited from an O(1) merged List. It's not just for the Haskell-like This may be useful when for example to build a Guava Whereas if we have O(1) concatenation, the process of range split and overlapping detection will be more efficient. After we are done with the range split, we can then do a final O(n) transformation from the concatenation-optimized data structure to a standard List. The API should be immutable, and we probably shouldn't name it @Immutable
public final class Chain<T> {
public static <T> Chain<T> of(T element);
public static <T> Chain<T> of(T element, T... remaining);
// O(1) operations to concat
public static <T> Chain<T> concat(Chain<? extends T> left, Chain<? extends T> right);
public Chain<T> concat(T element);
// O(n) operations to consume the elements
public Stream<T> stream();
public <R> R collect(Collector<T, ?, R> collector);
} One question is about hashCode/equals. It seems like we'll have to first collect the elements to a List before being to compare, which will be O(n). Can't seem to think of an efficient alternative (but maybe we can make it lazily-initialized to pay the cost only once). |
Beta Was this translation helpful? Give feedback.
-
Just added a I ended up making it a subtype of Overall, user are expected to read from it still as a List. But they can concatenate it using O(1) operations. |
Beta Was this translation helpful? Give feedback.
-
That looks great! Question: |
Beta Was this translation helpful? Give feedback.
-
The functional languages support List that can be "prepended" to functionally. That is,
cons(1, [2, 3]
results in[1, 2, 3]
.I have a use case to frequently merge lists, so it's nice if I can do it faster than O(n).
Beta Was this translation helpful? Give feedback.
All reactions