Skip to content

Instantly share code, notes, and snippets.

@gdevanla
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gdevanla/9393161 to your computer and use it in GitHub Desktop.
Save gdevanla/9393161 to your computer and use it in GitHub Desktop.
Clojure like partition-by function for groovy
//Accepts a closure that takes one argument. The closure should return true/false.
//The closure is the predicate which will be checked to create new partitions
def partition(coll, Closure cond) {
def x = coll.drop(1).inject([[coll[0]]]) { acc, it ->
if ( cond(it) ) {
acc << [it]
}
else
{
acc[-1] << it
}
acc
}
}
//Example
def l = [ 3, 1, 2, 3, 4, 5, 3, 7, 3, 9, 10]
println partition(l) { it == 3}
//Output
>> [[3, 1, 2], [3, 4, 5], [3, 7], [3, 9, 10]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment