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

com.github.tonivade.purefun.optics.POptional Maven / Gradle / Ivy

/*
 * Copyright (c) 2018-2019, Antonio Gabriel Muñoz Conejo 
 * Distributed under the terms of the MIT License
 */
package com.github.tonivade.purefun.optics;

import static com.github.tonivade.purefun.Function1.identity;
import static java.util.Objects.requireNonNull;

import com.github.tonivade.purefun.Function1;
import com.github.tonivade.purefun.Function2;
import com.github.tonivade.purefun.type.Either;
import com.github.tonivade.purefun.type.Option;

public final class POptional {

  private final Function1> set;
  private final Function1> getOrModify;

  protected POptional(Function1> set, Function1> getOrModify) {
    this.set = requireNonNull(set);
    this.getOrModify = requireNonNull(getOrModify);
  }

  public static  POptional of(Function2 set, Function1> getOrModify) {
    return new POptional<>(set.curried(), getOrModify);
  }

  public Function1 set(S target) {
    return set.apply(target);
  }

  public T set(S target, B value) {
    return set(target).apply(value);
  }

  public Either getOrModify(S target) {
    return getOrModify.apply(target);
  }

  public Option getOption(S target) {
    return getOrModify(target).toOption();
  }

  public Function1 lift(Function1 mapper) {
    return target -> modify(target, mapper);
  }

  public T modify(S target, Function1 mapper) {
    return getOrModify(target).fold(identity(), value -> set(target, mapper.apply(value)));
  }

  public Option modifyOption(S target, Function1 mapper) {
    return getOption(target).map(value -> set(target, mapper.apply(value)));
  }

  public  POptional compose(POptional other) {
    return new POptional<>(
        target -> value -> this.modify(target, a -> other.set(a, value)),
        target -> this.getOrModify(target).flatMap(a -> other.getOrModify(a).bimap(b -> this.set(target, b), identity())) );
  }

  public  POptional compose(PIso other) {
    return compose(other.asOptional());
  }

  public  POptional compose(PPrism other) {
    return compose(other.asOptional());
  }

  public  POptional compose(PLens other) {
    return compose(other.asOptional());
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy