Pregunta

As a beginner in both java8 and functional programming, I think I'm missing something when reading about function composition since I cannot find a reason why there are two methods that do this, andThen and compose.

Since f.andThen(g) is exactly the same as g.compose(f), why are both needed, in which cases would using one of them be better than the other?

¿Fue útil?

Solución

compose is a traditional operation. Its order was decided by mathematicians. However, like a lot of things originally decided by mathematicians, the order isn't a very convenient convention for programmers. We include the operation anyway because functional programming has strong ties to mathematics.

In languages like Haskell, you only have the compose operator, so you have to read and write everything backwards, like:

filter even . concat . filter ((> 2) . length)

The filter for length greater than 2 happens first, then the concat, then the filter for even numbers. You get used to this, but it's still annoying, so other languages create compose operators like andThen that let you write a composed function in the order it executes. Anyone could easily add such an operator to their program in Haskell too, for that matter, it just wouldn't be idiomatic Haskell any more.

Feel free to use whichever one makes it easier for you to translate from your domain.

Otros consejos

=v= There is also a BiFunction interface that does for two arguments what Function does for one. This interface has no compose because that won't work on two arguments, but it does have andThen. So one advantage of Function#andThen is consistency with BiFunction.

Licenciado bajo: CC-BY-SA con atribución
scroll top