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

com.jnape.palatable.lambda.monoid.builtin.First 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.monoid.Monoid;

import static com.jnape.palatable.lambda.adt.Maybe.nothing;
import static com.jnape.palatable.lambda.functions.builtin.fn1.CatMaybes.catMaybes;
import static com.jnape.palatable.lambda.functions.builtin.fn1.Head.head;
import static com.jnape.palatable.lambda.functions.builtin.fn2.Map.map;

/**
 * A {@link Monoid} instance formed by {@link Maybe}<A>. The application to two {@link Maybe} values
 * produces the first non-empty value, or {@link Maybe#nothing()} if all values are empty.
 *
 * @param  the Maybe value parameter type
 * @see Last
 * @see Present
 * @see Monoid
 * @see Maybe
 */
public final class First implements Monoid> {

    private static final First INSTANCE = new First<>();

    private First() {
    }

    @Override
    public Maybe identity() {
        return nothing();
    }

    @Override
    public Maybe checkedApply(Maybe x, Maybe y) {
        return x.fmap(Maybe::just).orElse(y);
    }

    @Override
    public  Maybe foldMap(Fn1> fn, Iterable bs) {
        return head(catMaybes(map(fn, bs)));
    }

    @SuppressWarnings("unchecked")
    public static  First first() {
        return (First) INSTANCE;
    }

    public static  Fn1, Maybe> first(Maybe x) {
        return First.first().apply(x);
    }

    public static  Maybe first(Maybe x, Maybe y) {
        return first(x).apply(y);
    }
}