What is function composition?
It all has to do with creating small reusable functions that you can combine to compose new functions.
Now, how can we achieve this using compose and andThen?
Let's first define two simple functions - times2 and squared.
- Function
times2 = e -> e * 2; - Function
squared = e -> e * e;
- times2.compose(squared).apply(4);
- // Returns 32 = (4^2) * 2
- times2.andThen(squared).apply(4);
- // Returns 64 = (4*2)^2
Let's start composing functions
Let's create an example to see how we can use this approach to create small pieces of reusable code - then put them together in different ways. Consider the following. We have a list of articles and we need to filter the articles based on different requirements. Let's start by introducing two basic functions - byAuthor and byTag - that filter articles based on an author and a tag.
- BiFunction
, List > byAuthor = - (name, articles) -> articles.stream()
- .filter(a -> a.getAuthor().equals(name))
- .collect(Collectors.toList());
- BiFunction
, List > byTag = - (tag, articles) -> articles.stream()
- .filter(a -> a.getTags().contains(tag))
- .collect(Collectors.toList());
Since BiFunction takes two arguments, it only offers the andThen function. You can't put the result of a function into a function that takes two arguments, hence the lack of the compose function. Moving on - let's also throw in a basic function that sorts a list of articles from newest to oldest and a function that returns the first article a list.
- Function
- , List
> sortByDate = - articles -> articles.stream()
- .sorted((x, y) -> y.published().compareTo(x.published()))
- .collect(Collectors.toList());
- Function
- , Optional
> first = a -> a.stream().findFirst();
- Function
- , Optional
> newest = first.compose(sortByDate);
- BiFunction
, Optional > newestByAuthor = byAuthor.andThen(newest);
- BiFunction
, List > byAuthorSorted = - byAuthor.andThen(sortByDate);
Or maybe you don't care about the author. You just want the newest article based on your favourite tag.
- BiFunction
, Optional > newestByTag = - byTag.andThen(newest);
沒有留言:
張貼留言