Created
September 9, 2012 23:59
-
-
Save quux00/3688012 to your computer and use it in GitHub Desktop.
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
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