groovy-comprehension icon indicating copy to clipboard operation
groovy-comprehension copied to clipboard

Is this a silly question?

Open emfanitek opened this issue 10 years ago • 1 comments

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.

emfanitek avatar Apr 23 '14 21:04 emfanitek

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   = []

uehaj avatar Apr 23 '14 21:04 uehaj