Skip to content

Instantly share code, notes, and snippets.

@Delors
Last active April 17, 2024 18:52
Show Gist options
  • Save Delors/456bf22817f107b8b9a54c8a7cd0ce86 to your computer and use it in GitHub Desktop.
Save Delors/456bf22817f107b8b9a54c8a7cd0ce86 to your computer and use it in GitHub Desktop.
A very simple template of a simple array based list for teaching purposes.
import java.util.function.BiFunction;
import java.util.function.Function;
public class FunctionalList<E> {
private E[] elements;
private int size;
@SuppressWarnings("unchecked")
public FunctionalList(int capacity) {
this.elements = (E[])new Object[capacity];
this.size = 0;
}
public void add(E e){
if (size == elements.length) {
throw new IllegalStateException("List is full");
}
elements[size] = e;
size++;
}
public E get(int index){
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index out of bounds");
}
return elements[index];
}
public <Y> Y foldLeft(Y startValue, BiFunction<Y, E, Y> f){ TODO }
public <Y> FunctionalList<Y> map(Function<E, Y> f){ TODO }
public static void main(String[] args) {
FunctionalList<String> l = new FunctionalList<>(10);
l.add("a");
l.add("bb");
l.add("ccc");
l.add("asdf");
FunctionalList<Integer> lengths = l.map(e -> e.length());
System.out.println(lengths.foldLeft("", (a, b) -> a + " " + b));
Integer totalLength = l.foldLeft(0, (a, b) -> a + b.length());
System.out.println(totalLength);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment