Created
January 22, 2014 13:41
-
-
Save davidallsopp/8558894 to your computer and use it in GitHub Desktop.
A generic Java method for taking the tails (progressively shorter sublists) of a List. Does not include the empty list (unlike the Haskell tails function), though this is trivially changed.
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
import java.util.*; | |
public class Tails { | |
/** Not including the empty list */ | |
public static <A> List<List<A>> tails(List<A> xs) { | |
ArrayList<List<A>> tails = new ArrayList<List<A>>(xs.size()); | |
for (int i = 0; i < xs.size(); i++) { | |
ArrayList<A> tail = new ArrayList<A>(xs.size() - i); | |
tails.add(tail); | |
for (List<A> ys : tails) { | |
ys.add(xs.get(i)); | |
} | |
} | |
return tails; | |
} | |
public static void main(String[] args) { | |
String[] words = { "the", "cat", "sat", "on", "the", "mat" }; | |
List<String> xs = Arrays.asList(words); | |
System.out.println(tails(xs)); | |
// [[the, cat, sat, on, the, mat], [cat, sat, on, the, mat], [sat, on, the, mat], [on, the, mat], [the, mat], [mat]] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment