All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.jnape.palatable.lambda.monoid.builtin.Present Maven / Gradle / Ivy

There is a newer version: 5.5.0
Show newest version
package com.jnape.palatable.lambda.monoid.builtin;

import com.jnape.palatable.lambda.adt.Maybe;
import com.jnape.palatable.lambda.functions.Fn1;
import com.jnape.palatable.lambda.functions.specialized.MonoidFactory;
import com.jnape.palatable.lambda.monoid.Monoid;
import com.jnape.palatable.lambda.semigroup.Semigroup;
import com.jnape.palatable.lambda.semigroup.builtin.Absent;

import static com.jnape.palatable.lambda.adt.Maybe.nothing;
import static com.jnape.palatable.lambda.monoid.Monoid.monoid;
import static com.jnape.palatable.lambda.monoid.builtin.First.first;

/**
 * A {@link Monoid} instance formed by {@link Maybe}<A> and a semigroup over A. The
 * application to two {@link Maybe} values is presence-biased, such that for a given {@link Maybe} x
 * and y:
 * 
    *
  • if x is present and y is absent, the result is x
  • *
  • if x is absent, the result is y
  • *
  • if both x and y are present, the result is the application of the x and y values in * terms of the provided semigroup, wrapped in {@link Maybe#just}
  • *
* * @param the Maybe value parameter type * @see Monoid * @see Absent * @see Maybe */ public final class Present implements MonoidFactory, Maybe> { private static final Present INSTANCE = new Present<>(); private Present() { } @Override public Monoid> checkedApply(Semigroup aSemigroup) { return monoid((maybeX, maybeY) -> first(maybeX.fmap(x -> maybeY.fmap(aSemigroup.apply(x)).orElse(x)), maybeY), nothing()); } @SuppressWarnings("unchecked") public static Present present() { return (Present) INSTANCE; } public static Monoid> present(Semigroup semigroup) { return Present.present().apply(semigroup); } public static Fn1, Maybe> present(Semigroup aSemigroup, Maybe x) { return present(aSemigroup).apply(x); } public static Maybe present(Semigroup semigroup, Maybe x, Maybe y) { return present(semigroup, x).apply(y); } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy