-
-
Notifications
You must be signed in to change notification settings - Fork 27k
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
januslinhc
wants to merge
24
commits into
iluwatar:master
from
januslinhc:future/add-currying-pattern
Closed
Add currying pattern #1855
Changes from all commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
6799622
Add currying pattern code
januslinhc e3b9585
Add currying pattern code
januslinhc 79327dc
Add currying pattern code
januslinhc 7e4bc40
Add README for currying
januslinhc 367b870
Merge branch 'master' into future/add-currying-pattern
januslinhc a9f875b
Remove wrong credit
januslinhc 1b902bf
fix parent module version
januslinhc 1ab9f4f
Merge remote-tracking branch 'origin/master' into future/add-currying…
januslinhc 221e031
fix style
januslinhc b5c50ed
add maven-assembly-plugin
januslinhc 7e4c34c
Use Lombok to get rid of boilerplate
januslinhc 8cd16fe
Update tags in README.md
januslinhc 077bd45
Update categories in README.md
januslinhc bcedc3f
add language in README.md
januslinhc 6332fdd
update Tutorials and Credits sections in README.md
januslinhc ab93ab5
add test case for main
januslinhc 2571962
Merge remote-tracking branch 'origin/master' into future/add-currying…
januslinhc 20466c4
fix merge conflict
januslinhc 4a93b25
revert dao change
januslinhc 9928e70
remove diagram
januslinhc 34e80af
add test cases
januslinhc b617468
remove unused import
januslinhc fa9d7cc
improve README.md
januslinhc 26f4cae
fix style
januslinhc File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
|
||
--- | ||
|
||
## 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); | ||
} | ||
``` | ||
|
||
januslinhc marked this conversation as resolved.
Show resolved
Hide resolved
|
||
## 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/) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | ||
januslinhc marked this conversation as resolved.
Show resolved
Hide resolved
|
||
</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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
58
currying/src/test/java/com/iluwatar/currying/StaffTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.