Skip to content

Instantly share code, notes, and snippets.

@bkyrlach
Created July 26, 2012 16:46
Show Gist options
  • Select an option

  • Save bkyrlach/3183152 to your computer and use it in GitHub Desktop.

Select an option

Save bkyrlach/3183152 to your computer and use it in GitHub Desktop.
List comparison...
import java.util.ArrayList;
import java.util.List;
public class EmptyList {
//We can try and define a constant for empty List in Java too...
//But we have a problem. What type should the list be?
//We don't want to create a constant for each kind of empty list.
//The only choice seems to be Object... that can't be a good sign.
public static final List<Object> el = new ArrayList<Object>();
//Array lists obviously don't have cons, but we can certainly
//try to define such a generic method...
public static <T> List<T> cons(T t, List<T> l) {
List<T> retval = new ArrayList<T>();
retval.add(t);
retval.addAll(l);
return retval;
}
//Lets see how we use it.
public static void main(String[] args) {
List<String> a = cons("a", el); //Ruh-roh... doesn't compile.
List<Integer> b = cons(2, el); //Same as above.
List<Object> c = cons("a", el); //This works, but we've defeated our type system. :(
List<Object> d = cons(2, cons("a", el)); //So, sort of like Clojure, but how very icky.
}
}
;For example purposes, we can use a named constant for empty list...
(def el ())
;We like Clojure because we can work with lists naturally.
;We can add to a list...
(cons :a el) ;Yields (:a)
;We can even add mixed types to a list...
(cons 2 (cons :a el))
;And we don't have to fight the type system to use lists...
(def somelist (cons 2 (cons :a el)))
(rest somelist) ;Yields (:a)
(first somelist) ;Yields 2
;rest and first are just like any Clojure functions we might want to define.
import java.util.ArrayList;
import java.util.List;
public class NullEmptyList {
//"null" is already a constant defined in the system, so we have no need
//of a named constant for empty list.
public static <T> List<T> cons(T t, List<T> l) {
List<T> retval = new ArrayList<T>();
retval.add(t);
//We are using null here to represent an empty list.
if(l != null) {
retval.addAll(l);
}
return retval;
}
public static void main(String[] args) {
List<String> a = cons("a", null); //This works as expected.
List<Integer> b = cons(2, null); //This also works as expected.
List<Object> c = cons(2, cons("a", null)); //This doesn't work. Perhaps this is what the argument should focus on?
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment