Skip to content

Instantly share code, notes, and snippets.

@ankurpshah
Created July 27, 2013 10:14
Show Gist options
  • Save ankurpshah/6094466 to your computer and use it in GitHub Desktop.
Save ankurpshah/6094466 to your computer and use it in GitHub Desktop.
Pattern matching example
package datastructures;
// Possible syntax extensions; won't compile for any version of Java.
public class PatternMatchExample {
public static String match(Object obj) {
switch (obj) {
case EMPTY:
// Is it an empty list?
return "()";
case NonEmptyList(1, 2): // A list with 1 and 2?
return "(1,(2,())";
case List<?> list(head,tail): // Any other List? Create head, tail variables
return "("+head+","+match(tail)+")";
default:
// Not a List!!
return "unrecognized object!";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment