Initial data commit
This commit is contained in:
parent
72d218235f
commit
f23f22d71c
199087 changed files with 3378941 additions and 0 deletions
54
Task/Monads-Writer-monad/Java/monads-writer-monad.java
Normal file
54
Task/Monads-Writer-monad/Java/monads-writer-monad.java
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
import java.util.function.Function;
|
||||
|
||||
public final class MonadWriter {
|
||||
|
||||
public static void main(String[] aArgs) {
|
||||
Monad<Double> initial = Monad.unit(5.0, "Initial value");
|
||||
Monad<Double> result = initial.bind(MonadWriter::root).bind(MonadWriter::addOne).bind(MonadWriter::half);
|
||||
System.out.println("The Golden Ratio is " + result.getValue() + System.lineSeparator());
|
||||
System.out.println("This was derived as follows:" + System.lineSeparator() + result.getText());
|
||||
}
|
||||
|
||||
private static Monad<Double> root(double aD) {
|
||||
return Monad.unit(Math.sqrt(aD), "Took square root");
|
||||
}
|
||||
|
||||
private static Monad<Double> addOne(double aD) {
|
||||
return Monad.unit(aD + 1.0, "Added one");
|
||||
}
|
||||
|
||||
private static Monad<Double> half(double aD) {
|
||||
return Monad.unit(aD / 2.0, "Divided by two");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
final class Monad<T> {
|
||||
|
||||
public static <T> Monad<T> unit(T aValue, String aText) {
|
||||
return new Monad<T>(aValue, aText);
|
||||
}
|
||||
|
||||
public Monad<T> bind(Function<T, Monad<T>> aFunction) {
|
||||
Monad<T> monad = aFunction.apply(value);
|
||||
monad.text = text + monad.text;
|
||||
return monad;
|
||||
}
|
||||
|
||||
public T getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
private Monad(T aValue, String aText) {
|
||||
value = aValue;
|
||||
text = String.format("%-21s%s%n", " " + aText, ": " + aValue);
|
||||
}
|
||||
|
||||
private T value;
|
||||
private String text;
|
||||
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue