Created
July 27, 2013 10:14
-
-
Save ankurpshah/6094466 to your computer and use it in GitHub Desktop.
Pattern matching example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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