Browser docs

Currying

Name / classification

Currying

Intent

Currying decomposes a function that takes multiple arguments into a sequence of functions that each take a single argument. Curried functions are useful since they can be used to create new functions with lower arity to perform more specialised tasks in a concise and readable manner. This is done via partial application.

Explanation

Real-world example

Consider a librarian who wants to populate their library with books. The librarian wants functions which can create books corresponding to specific genres and authors. Currying makes this possible by writing a curried book builder function and utilising partial application.

In plain words

Decompose a function that take multiple arguments into multiple functions that take a single argument.

Wikipedia says

Currying is the technique of converting a function that takes multiple arguments into a sequence of functions that each take a single argument. Given a function $f:(X \times Y) \rightarrow Z$, currying constructs a new function $h:X \rightarrow (Y\rightarrow Z)$. $h$ takes an argument from $X$ and returns a function which maps $Y$ to $Z$. Hence, $h(x)(y) = f(x, y)$.

Programmatic example
We have a Book class and Genre enum.

 1public class Book {
 2  private final Genre genre;
 3  private final String author;
 4  private final String title;
 5  private final LocalDate publicationDate;
 6
 7  Book(Genre genre, String author, String title, LocalDate publicationDate) {
 8    this.genre = genre;
 9    this.author = author;
10    this.title = title;
11    this.publicationDate = publicationDate;
12  }
13}
14
15public enum Genre {
16  FANTASY,
17  HORROR,
18  SCI_FI;
19}

We could easily create a Book object with the following method:

1Book createBook(Genre genre, String author, String title, LocalDate publicationDate) {
2    return new Book(genre, author, title, publicationDate);
3}

However, what if we only wanted to create books from the FANTASY genre? We could pass in the FANTASY parameter on each method call; however, this is repetitive. We could define a new method specifically for creating FANTASY books; however, it is infeasible to create a new method for each book genre. The solution is to create a curried function.

1static Function<Genre, Function<String, Function<String, Function<LocalDate, Book>>>> book_creator
2      = genre
3      -> author
4      -> title
5      -> publicationDate
6      -> new Book(genre, author, title, publicationDate);

Note that the order of the parameters is important. genre must come before author, author must come before title and so on. We must be considerate of this when writing curried functions to take full advantage of partial application. Using the above function, we can define a new function fantasyBookFunc, to generate FANTASY books as follows:

1Function<String, Function<String, Function<LocalDate, Book>>> fantasyBookFunc = Book.book_creator.apply(Genre.FANTASY);

Unfortunately, the type signature of BOOK_CREATOR and fantasyBookFunc are difficult to read and understand. We can improve this by using the builder pattern and functional interfaces.

 1public static AddGenre builder() {
 2    return genre
 3        -> author
 4        -> title
 5        -> publicationDate
 6        -> new Book(genre, author, title, publicationDate);
 7}
 8
 9public interface AddGenre {
10Book.AddAuthor withGenre(Genre genre);
11}
12
13public interface AddAuthor {
14Book.AddTitle withAuthor(String author);
15}
16
17public interface AddTitle {
18Book.AddPublicationDate withTitle(String title);
19}
20
21public interface AddPublicationDate {
22Book withPublicationDate(LocalDate publicationDate);
23}

The semantics of the builder function can easily be understood. The builder function returns a function AddGenre, which adds the genre to the book. Similarity, the AddGenre function returns another function AddTitle, which adds the title to the book and so on, until the AddPublicationDate function returns a Book. For example, we could create a Book as follows:

1Book book = Book.builder().withGenre(Genre.FANTAST)
2        .withAuthor("Author")
3        .withTitle("Title")
4        .withPublicationDate(LocalDate.of(2000, 7, 2));

The below example demonstrates how partial application can be used with the builder function to create specialised book builder functions.

 1public static void main(String[] args) {
 2    LOGGER.info("Librarian begins their work.");
 3    
 4    // Defining genre book functions
 5    Book.AddAuthor fantasyBookFunc = Book.builder().withGenre(Genre.FANTASY);
 6    Book.AddAuthor horrorBookFunc = Book.builder().withGenre(Genre.HORROR);
 7    Book.AddAuthor scifiBookFunc = Book.builder().withGenre(Genre.SCI_FI);
 8
 9    // Defining author book functions
10    Book.AddTitle kingFantasyBooksFunc = fantasyBookFunc.withAuthor("Stephen King");
11    Book.AddTitle kingHorrorBooksFunc = horrorBookFunc.withAuthor("Stephen King");
12    Book.AddTitle rowlingFantasyBooksFunc = fantasyBookFunc.withAuthor("J.K. Rowling");
13
14    // Creates books by Stephen King (horror and fantasy genres)
15    Book shining = kingHorrorBooksFunc.withTitle("The Shining")
16    .withPublicationDate(LocalDate.of(1977, 1, 28));
17    Book darkTower = kingFantasyBooksFunc.withTitle("The Dark Tower: Gunslinger")
18    .withPublicationDate(LocalDate.of(1982, 6, 10));
19
20    // Creates fantasy books by J.K. Rowling
21    Book chamberOfSecrets = rowlingFantasyBooksFunc.withTitle("Harry Potter and the Chamber of Secrets")
22    .withPublicationDate(LocalDate.of(1998, 7, 2));
23
24    // Create sci-fi books
25    Book dune = scifiBookFunc.withAuthor("Frank Herbert")
26    .withTitle("Dune")
27    .withPublicationDate(LocalDate.of(1965, 8, 1));
28    Book foundation = scifiBookFunc.withAuthor("Isaac Asimov")
29    .withTitle("Foundation")
30    .withPublicationDate(LocalDate.of(1942, 5, 1));
31
32    LOGGER.info("Stephen King Books:");
33    LOGGER.info(shining.toString());
34    LOGGER.info(darkTower.toString());
35
36    LOGGER.info("J.K. Rowling Books:");
37    LOGGER.info(chamberOfSecrets.toString());
38
39    LOGGER.info("Sci-fi Books:");
40    LOGGER.info(dune.toString());
41    LOGGER.info(foundation.toString());
42}

Program output:

Librarian begins their work.
Stephen King Books:
Book{genre=HORROR, author='Stephen King', title='The Shining', publicationDate=1977-01-28}
Book{genre=FANTASY, author='Stephen King', title='The Dark Tower: Gunslinger', publicationDate=1982-06-10}
J.K. Rowling Books:
Book{genre=FANTASY, author='J.K. Rowling', title='Harry Potter and the Chamber of Secrets', publicationDate=1998-07-02}
Sci-fi Books:
Book{genre=SCI_FI, author='Frank Herbert', title='Dune', publicationDate=1965-08-01}
Book{genre=SCI_FI, author='Isaac Asimov', title='Foundation', publicationDate=1942-05-01}

Class diagram

currying-uml

Applicability

A curried function which has only been passed some of its arguments is called a partial application. Partial application allows for the creation of functions with some pre-defined data in their scope, since partial application can be used to create specialised functions with lower arity. This abstraction can help keep code readable and concise. Therefore, currying is useful when frequently calling functions with fixed parameters.

Known uses

Most functional programming languages support curried functions. A popular example is Haskell, in which all functions are considered curried.

Consequences

Pros

  • Currying allows for partial application, which can be used to create specialised functions concisely.

Cons

  • The order of the parameters in a curried function is important since we want to take advantage of partial application. It is best to input the most general parameters first and input specific parameters last.
  • As shown in the programmatic example above, curried functions with several parameters have a cumbersome type signature (in Java).

Credits