Skip to content

Instantly share code, notes, and snippets.

@lion137
Created July 8, 2019 08:27
Show Gist options
  • Save lion137/c9afe644ab7c6fb212f604c9faad927c to your computer and use it in GitHub Desktop.
Save lion137/c9afe644ab7c6fb212f604c9faad927c to your computer and use it in GitHub Desktop.
Functional list in Java - working proof of concept
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
interface List {
boolean is_empty();
int head();
List tail();
}
class Cons implements List {
int head;
List rest;
Cons (int _head, List _tail) {
head = _head;
rest = _tail;
}
public boolean is_empty() {
return false;
}
public int head() {
return this.head;
}
public List tail() {
return this.rest;
}
public String toString() {
if (this.tail().toString() == "()") return String.valueOf(this.head()) + ")";
else {
return "(" + String.valueOf(this.head()) + " " + this.tail().toString();
}
}
}
class Nil implements List{
private static Nil single = null;
public boolean is_empty() {
return true;
}
public int head() {
throw new IndexOutOfBoundsException();
}
public List tail() {
throw new IndexOutOfBoundsException();
}
public String toString() {
return "()";
}
public static Nil Nil() {
if (single == null) {
single = new Nil();
}
return single;
}
}
class Main {
static int length(List xs) {
if (xs.is_empty()) return 0;
else return 1 + length(xs.tail());
}
public static void main (String [] args) {
List list = new Cons(1, new Cons(2, new Nil()));
System.out.println(list);
System.out.println(length(list));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment