Skip to content

Add currying pattern #1855

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 128 additions & 0 deletions currying/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
---
layout: pattern title: Currying folder: currying permalink: /patterns/currying/ categories: Functional language: en
tags:

- Decoupling
Comment on lines +2 to +5
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The frontmatter looks somehow messed up. Please check it.


---

## Intent

Currying pattern transforms an arbitrary arity into a sequence of unary functions.

## Explanation

Real-world example

> We have a Staff class for storing employees' information, e.g. firstName, lastName,
> gender, email, etc. We want to adapt currying pattern to simplify the parameters handling,
> we don't need to provide all parameters at the same time. We can provide them one by one
> when we have that data.

In plain words

> It helps you to avoid passing the same variable again and again.
> It helps to create a higher order function. It extremely helpful in event handling.
> Little snippets of code can be written and reused with ease.

Wikipedia says

> Currying provides a way for working with functions that take multiple arguments,
> and using them in frameworks where functions might take only one argument.
> For example, some analytical techniques can only be applied to functions with a
> single argument. Practical functions frequently take more arguments than this.
> Frege showed that it was sufficient to provide solutions for the single argument
> case, as it was possible to transform a function with multiple arguments into a
> chain of single-argument functions instead. This transformation is the process
> now known as currying.

**Programmatic Example**

First, we have the `Staff` class:

```java

@AllArgsConstructor
@Data
public class Staff {
private String firstName;
private String lastName;
private Gender gender;
private String email;
private LocalDate dateOfBirth;
}
```

By using @AllArgsConstructor from Lombok library, it will generate a constructor with all attributes. All paramaters
need to provide at the same time.

Next, we will try to use Curry pattern to transforms an arbitrary arity into a sequence of unary functions.

```java
static Function<String,
Function<String,
Function<Gender,
Function<String,
Function<LocalDate, Staff>>>>>CREATOR=
firstName->lastName
->gender->email
->dateOfBirth
->new Staff(firstName,lastName,gender,
email,dateOfBirth);
```

With using this way, we can create Staff object by providing parameters one by one:

```java
Staff.CREATOR
.apply(firstName)
.apply(lastName)
.apply(gender)
.apply(email)
.apply(dateOfBirth);
```

We can also use Functional Interface to implement currying function.

```java
static AddFirstName builder(){
return firstName->lastName
->gender->email
->dateOfBirth
->new Staff(firstName,lastName,gender,email,dateOfBirth);
}

interface AddFirstName {
AddLastName withReturnFirstName(String firstName);
}

interface AddLastName {
AddGender withReturnLastName(String lastName);
}

interface AddGender {
AddEmail withReturnGender(Gender gender);
}

interface AddEmail {
AddDateOfBirth withReturnEmail(String email);
}

interface AddDateOfBirth {
Staff withReturnDateOfBirth(LocalDate dateOfBirth);
}
```

## Applicability

Use the currying pattern in any of the following situations

* when you want to break a function with many arguments into many functions with single argument

## Tutorials

* [Currying in Java](https://www.baeldung.com/java-currying)

## Credits

* [Baeldung](https://www.baeldung.com/)
62 changes: 62 additions & 0 deletions currying/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--

The MIT License
Copyright (c) 2014-2016 Ilkka Seppälä

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>java-design-patterns</artifactId>
<groupId>com.iluwatar</groupId>
<version>1.25.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>currying</artifactId>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<configuration>
<archive>
<manifest>
<mainClass>com.iluwatar.dao.App</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
97 changes: 97 additions & 0 deletions currying/src/main/java/com/iluwatar/currying/Staff.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
package com.iluwatar.currying;

import java.time.LocalDate;
import java.util.function.Function;
import lombok.AllArgsConstructor;
import lombok.Data;

/**
* Staff Object for demonstrating how to use currying pattern.
*/
@AllArgsConstructor
@Data
public class Staff {
private String firstName;
private String lastName;
private Gender gender;
private String email;
private LocalDate dateOfBirth;

/**
* Use {@link Function} for currying.
*/
static Function<String,
Function<String,
Function<Gender,
Function<String,
Function<LocalDate, Staff>>>>> CREATOR =
firstName -> lastName
-> gender -> email
-> dateOfBirth
-> new Staff(firstName, lastName, gender,
email, dateOfBirth);

/**
* Use functional interfaces for currying.
*/
static AddFirstName builder() {
return firstName -> lastName
-> gender -> email
-> dateOfBirth
-> new Staff(firstName, lastName, gender, email, dateOfBirth);
}

interface AddFirstName {
AddLastName withReturnFirstName(String firstName);
}

interface AddLastName {
AddGender withReturnLastName(String lastName);
}

interface AddGender {
AddEmail withReturnGender(Gender gender);
}

interface AddEmail {
AddDateOfBirth withReturnEmail(String email);
}

interface AddDateOfBirth {
Staff withReturnDateOfBirth(LocalDate dateOfBirth);
}

enum Gender {
Male, Female
}

/**
* Main method for maven-assembly-plugin.
*/
public static void main(String[] args) {
final String firstName = "Janus";
final String lastName = "Lin";
final Staff.Gender gender = Staff.Gender.Male;
final String email = "[email protected]";
final LocalDate dateOfBirth = LocalDate.now();

Staff staff1 = Staff.CREATOR
.apply(firstName)
.apply(lastName)
.apply(gender)
.apply(email)
.apply(dateOfBirth);

System.out.println(String.format("Staff created with basic currying: %s", staff1));

Staff staff2 = Staff.builder()
.withReturnFirstName(firstName)
.withReturnLastName(lastName)
.withReturnGender(gender)
.withReturnEmail(email)
.withReturnDateOfBirth(dateOfBirth);

System.out.println(
String.format("Staff created with currying and functional interfaces: %s", staff2));
}
}
58 changes: 58 additions & 0 deletions currying/src/test/java/com/iluwatar/currying/StaffTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package com.iluwatar.currying;

import org.junit.Assert;
import org.junit.Test;

import java.time.LocalDate;

import static org.junit.Assert.*;

public class StaffTest {
private final String firstName = "Janus";
private final String lastName = "Lin";
private final Staff.Gender gender = Staff.Gender.Male;
private final String email = "[email protected]";
private final LocalDate dateOfBirth = LocalDate.now();

private final Staff expectedResult = new Staff(firstName, lastName, gender, email, dateOfBirth);

@Test
public void createStaffWithBasicCurrying() {
Staff actualResult = Staff.CREATOR
.apply(firstName)
.apply(lastName)
.apply(gender)
.apply(email)
.apply(dateOfBirth);
assertEquals(expectedResult, actualResult);
}

@Test
public void createStaffWithFunctionalInterface() {
Staff actualResult = Staff.builder()
.withReturnFirstName(firstName)
.withReturnLastName(lastName)
.withReturnGender(gender)
.withReturnEmail(email)
.withReturnDateOfBirth(dateOfBirth);
assertEquals(expectedResult, actualResult);
}

@Test
public void mainTest() {
Staff.main(new String[]{});
}

@Test
public void hashTest() {
expectedResult.hashCode();
}

@Test
public void equalTest() {
assertTrue(expectedResult.equals(expectedResult));
assertFalse(expectedResult.equals(new Integer(1)));
Staff o2 = new Staff(firstName, lastName, gender, email, dateOfBirth);
assertTrue(expectedResult.equals(o2));
}
}
Loading