Skip to content

Instantly share code, notes, and snippets.

@quux00
Created September 9, 2012 23:59
Show Gist options
  • Save quux00/3688012 to your computer and use it in GitHub Desktop.
Save quux00/3688012 to your computer and use it in GitHub Desktop.
def ds1 = [1, 2, [3, 4, [5, "a"]]];
def isSequential(x) {
x instanceof Collection
}
def mapcat(f, coll) {
coll.inject([]) { x, y ->
def res = f(y)
if (isSequential(res)) {
x + res
} else {
x << f(y)
}
}
}
def flat2(ds) {
if (isSequential(ds)) {
mapcat(this.&flat2, ds);
} else {
[ds]
}
}
def flat3(ds) {
ds.inject([]) { x, y ->
if (isSequential(y)) {
x = x + flat3(y)
} else {
x << y;
}
}
}
println flat2(ds1);
println flat3(ds1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment