-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
f797c78
commit dc63d11
Showing
4 changed files
with
52 additions
and
2 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
This file contains 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,36 @@ | ||
package com.soumakis.control; | ||
|
||
import java.util.function.Function; | ||
|
||
/** | ||
* Reader monad implementation. This is a simple implementation of the Reader monad. It is used to | ||
* pass a context to a computation. The computation is a function that takes the context as an | ||
* argument and returns a value. The Reader monad allows us to chain computations that depend on the | ||
* context without passing the context explicitly. | ||
* | ||
* @param <C> the context type | ||
* @param <T> the result type | ||
*/ | ||
public class Reader<C, T> { | ||
|
||
private final Function<C, T> computation; | ||
|
||
private Reader(Function<C, T> computation) { | ||
this.computation = computation; | ||
} | ||
|
||
/** | ||
* Runs the computation with the given context. | ||
* | ||
* @param context the context | ||
* @return the result of the computation | ||
*/ | ||
public T run(C context) { | ||
return computation.apply(context); | ||
} | ||
|
||
public static <C, T> Reader<C, T> of(Function<C, T> computation) { | ||
return new Reader<>(computation); | ||
} | ||
|
||
} |
This file contains 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,14 @@ | ||
package com.soumakis.control; | ||
|
||
import org.junit.jupiter.api.Test; | ||
|
||
public class ReaderTest { | ||
|
||
@Test | ||
void testRun() { | ||
Reader<Integer, Integer> reader = Reader.of((Integer context) -> context + 1); | ||
|
||
assert (reader.run(1) == 2); | ||
} | ||
|
||
} |