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

jsonvalues.Option Maven / Gradle / Ivy

package jsonvalues;

import java.util.Optional;
import java.util.function.Function;

/**
 An Optional is an optic that allows seeing into a structure and getting, setting, or modifying an optional focus.
 It combines the properties of a Lens (getting, setting, and modifying) with the properties of a Prism (an optional focus).
 An  Optional can be seen as a pair of functions:
 {@code
 - get: S      => Optional[T]
 - set: (T, S) => S
 }
 A Optional could also be defined as a weaker Lens and weaker Prism

 @param  the source of an optional
 @param  the target of an optional */
public class Option {
    /**
     get the target of an Optional or nothing if there is no target
     */
    public final Function> get;

    /**
     function to look into S, set a value for an optional focus T, and obtain the modified source
     */
    public final Function> set;

    /**
     modify the target of an optional with a function if it exists, returing the same source otherwise
     */
    public final Function, Function> modify;

    Option(final Function> get,
           final Function> set
          ) {
        this.get = get;
        this.set = set;

        this.modify = f -> json ->
        {
            final Optional value = get.apply(json);
            if (!value.isPresent()) return json;
            return set.apply(f.apply(value.get()))
                      .apply(json);
        };
    }


    /**
     compose this optional with the given as parameter
     @param other the other optional
     @param  the type of the focus
     @return a new optional
     */
    public  Option compose(final Option other){
        return new Option<>(s -> {
            Optional t = this.get.apply(s);
            if(t.isPresent()) return other.get.apply(t.get());
            else return Optional.empty();
        }, f -> s -> {
            Optional t = this.get.apply(s);
            if(t.isPresent()) return this.set.apply(other.set.apply(f).apply(t.get())).apply(s);
            else return s;
        });
    }

}








© 2015 - 2025 Weber Informatics LLC | Privacy Policy