groovy-comprehension
groovy-comprehension copied to clipboard
Is this a silly question?
In groovyx.comprehension.extension.ListComprehensionExtension you use the following code:
static List bind(List self, @DelegatesTo(List) Closure c) { // Haskell's >>=
c.delegate = self
self.collect(c).inject([], {acc,elem->acc+elem})
}
What do you gain by using inject after collect? This creates a new list, that is identical to the original collected list.
Hi, In short, the purpose of inject is flatten the list. In Scala, bind is called 'flatMap' means "Apply map and then flatten". So in this case inject make the list flatten.
[[1,2,3], [4,5,6]].inject([], {acc,elem->acc+elem}) == [1, 2, 3, 4, 5, 6]
In haskell, list is a instance of monad with definition of '>>=' in following:
instance Monad [] where
m >>= f = concat (map f m) -- map(==groovy's collect) and then flatten by concat
return x = [x]
fail s = []