Skip to content

Commit

Permalink
Introducing Reader monad
Browse files Browse the repository at this point in the history
  • Loading branch information
VassilisSoum committed Aug 14, 2024
1 parent f797c78 commit dc63d11
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 2 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ Then, you can add the dependency to your project.
<dependency>
<groupId>com.github.VassilisSoum</groupId>
<artifactId>FunctionalUtils</artifactId>
<version>2.0.0</version>
<version>2.1.0</version>
</dependency>
```

Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<groupId>com.soumakis</groupId>
<artifactId>FunctionalUtils</artifactId>
<version>2.0.0</version>
<version>2.1.0</version>
<packaging>jar</packaging>

<properties>
Expand Down
36 changes: 36 additions & 0 deletions src/main/java/com/soumakis/control/Reader.java
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);
}

}
14 changes: 14 additions & 0 deletions src/test/java/com/soumakis/control/ReaderTest.java
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);
}

}

0 comments on commit dc63d11

Please sign in to comment.