mirror of
https://github.com/PolyhedralDev/Terra.git
synced 2026-06-23 21:14:26 +00:00
implement Monad (Maybe a)
This commit is contained in:
@@ -10,9 +10,9 @@ import java.util.function.Function;
|
|||||||
* A monad is a monoid in the category of endofunctors.
|
* A monad is a monoid in the category of endofunctors.
|
||||||
*/
|
*/
|
||||||
public interface Monad<T, M extends Monad<?, M>> extends Functor<T, M>, K<M, T> {
|
public interface Monad<T, M extends Monad<?, M>> extends Functor<T, M>, K<M, T> {
|
||||||
<T2, M2 extends Monad<?, M2>> Monad<T2, M2> bind(Function<T, Monad<T2, M2>> map);
|
<T2> Monad<T2, M> bind(Function<T, Monad<T2, M>> map);
|
||||||
|
|
||||||
<T1, M1 extends Monad<?, M1>> Monad<T1, M1> pure(T1 t);
|
<T1> Monad<T1, M> pure(T1 t);
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
default <U> Monad<U, M> map(Function<T, U> map) {
|
default <U> Monad<U, M> map(Function<T, U> map) {
|
||||||
|
|||||||
@@ -6,19 +6,44 @@ import java.util.Optional;
|
|||||||
import java.util.function.Function;
|
import java.util.function.Function;
|
||||||
|
|
||||||
|
|
||||||
public interface Maybe<T>{
|
public interface Maybe<T> extends Monad<T, Maybe<?>> {
|
||||||
|
@Override
|
||||||
|
default <T1> Maybe<T1> pure(T1 t) {
|
||||||
|
return just(t);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
<T2> Maybe<T2> bind(Function<T, Monad<T2, Maybe<?>>> map);
|
||||||
|
|
||||||
Optional<T> toOptional();
|
Optional<T> toOptional();
|
||||||
|
|
||||||
|
static <T1> Maybe<T1> just(T1 t) {
|
||||||
|
return new Just<>(t);
|
||||||
|
}
|
||||||
|
|
||||||
|
static <T1> Maybe<T1> nothing() {
|
||||||
|
return new Nothing<>();
|
||||||
|
}
|
||||||
|
|
||||||
record Just<T>(T value) implements Maybe<T> {
|
record Just<T>(T value) implements Maybe<T> {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Optional<T> toOptional() {
|
public Optional<T> toOptional() {
|
||||||
return Optional.of(value);
|
return Optional.of(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T2> Maybe<T2> bind(Function<T, Monad<T2, Maybe<?>>> map) {
|
||||||
|
return (Maybe<T2>) map.apply(value);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
record Nothing<T>() implements Maybe<T> {
|
record Nothing<T>() implements Maybe<T> {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T2> Maybe<T2> bind(Function<T, Monad<T2, Maybe<?>>> map) {
|
||||||
|
return nothing();
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Optional<T> toOptional() {
|
public Optional<T> toOptional() {
|
||||||
return Optional.empty();
|
return Optional.empty();
|
||||||
|
|||||||
Reference in New Issue
Block a user