Skip to content

Instantly share code, notes, and snippets.

@lispyclouds
Created April 15, 2021 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lispyclouds/c526783da1ad105b91389dcb10debe62 to your computer and use it in GitHub Desktop.
Save lispyclouds/c526783da1ad105b91389dcb10debe62 to your computer and use it in GitHub Desktop.
MWord.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.function.Function;
interface Result<T> {
<R> Result<R> then(Function<T, Result<R>> nextFn);
}
record Success<T>(T value) implements Result<T> {
@Override
public <R> Result<R> then(Function<T, Result<R>> nextFn) {
return nextFn.apply(this.value);
}
}
record Failure<T>(Throwable err) implements Result<T> {
@Override
@SuppressWarnings("unchecked")
public <R> Result<R> then(Function<T, Result<R>> nextFn) {
return (Result<R>) this;
}
}
public class M {
final static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static Result<Integer> readAndAdd(int prevNum) {
try {
System.out.print("Enter a number: ");
return new Success<>(prevNum + Integer.parseInt(br.readLine()));
} catch (Throwable e) {
return new Failure<>(e);
}
}
public static void main(String... args) {
final var result = new Success<Integer>(0)
.then(M::readAndAdd)
.then(M::readAndAdd)
.then(M::readAndAdd);
System.out.println(result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment