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

com.github.tonivade.purefun.optics.PLens 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.cons;
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;

public final class PLens {

  private final Function1 getter;
  private final Function1> setter;

  protected PLens(Function1 getter, Function1> setter) {
    this.getter = requireNonNull(getter);
    this.setter = requireNonNull(setter);
  }

  public static  PLens of(Function1 getter, Function2 setter) {
    return new PLens<>(getter, setter.curried());
  }

  public A get(S target) {
    return getter.apply(target);
  }

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

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

  public Function1 modify(Function1 mapper) {
    return target -> set(target).apply(mapper.apply(getter.apply(target)));
  }

  public Function1 modify(B newValue) {
    return modify(cons(newValue));
  }

  public POptional asOptional() {
    return POptional.of(this::set, getter.andThen(Either::right));
  }

  public  PLens compose(PLens other) {
    return new PLens<>(
        target -> other.get(this.get(target)),
        target -> value -> this.set(target).apply(other.modify(value).apply(this.get(target))));
  }

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

  public  PLens compose(PIso other) {
    return compose(other.asLens());
  }

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




© 2015 - 2025 Weber Informatics LLC | Privacy Policy