Last active
August 29, 2015 13:57
-
-
Save gdevanla/9393161 to your computer and use it in GitHub Desktop.
Clojure like partition-by function for groovy
This file contains 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
//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