
org.smallibs.data.MaybeHelper Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of hpas Show documentation
Show all versions of hpas Show documentation
Functional ADT And Asynchronous library in Java
/*
* HPAS
* https://github.com/d-plaindoux/hpas
*
* Copyright (c) 2016-2017 Didier Plaindoux
* Licensed under the LGPL2 license.
*/
package org.smallibs.data;
import org.smallibs.control.Functor;
import org.smallibs.control.Monad;
import org.smallibs.exception.NoValueException;
import org.smallibs.type.HK;
import java.util.function.Function;
public enum MaybeHelper {
;
public static Monad> monad(Maybe maybe) {
return new MaybeHelper.Monadic(maybe);
}
public static Try toTry(Maybe maybe) {
return maybe.map(Try::success).orElse(Try.failure(new NoValueException()));
}
@SuppressWarnings("unchecked")
private static > HK> specialize(HK app) {
return (HK>) app;
}
@SuppressWarnings("unchecked")
private static > HK generalize(HK> app) {
return (HK) app;
}
/**
* @param
*/
final static class Monadic implements Monad> {
private final Maybe aMaybe;
private Monadic(Maybe aMaybe) {
this.aMaybe = aMaybe;
}
@Override
public > HK map(Function super T, B> function) {
return generalize(new Monadic<>(aMaybe.map(function)));
}
@Override
public > HK flatmap(Function super T, HK> function) {
final Function> tMaybeFunction = t -> {
final HK apply = function.apply(t);
return specialize(apply).self();
};
return generalize(new Monadic<>(aMaybe.flatmap(tMaybeFunction)));
}
@Override
public T1 accept(Function>, T1> f) {
return aMaybe.accept(f);
}
@Override
public > HK apply(Functor, ?> functor) {
return generalize(new Monadic<>(aMaybe.flatmap(a -> {
final HK map = functor.map(bFunction -> bFunction.apply(a));
return specialize(map).self();
})));
}
@Override
public Maybe self() {
return aMaybe;
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy