
com.github.tonivade.purefun.optics.PIso Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of purefun-optics Show documentation
Show all versions of purefun-optics Show documentation
Functional Programming Library for Java
The newest version!
/*
* Copyright (c) 2018-2024, 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.core.Precondition.checkNonNull;
import com.github.tonivade.purefun.core.Function1;
import com.github.tonivade.purefun.type.Either;
public final class PIso {
private final Function1 get;
private final Function1 reverseGet;
PIso(Function1 get, Function1 reverseGet) {
this.get = checkNonNull(get);
this.reverseGet = checkNonNull(reverseGet);
}
public static PIso of(Function1 get, Function1 reverseGet) {
return new PIso<>(get, reverseGet);
}
public static PIso identity() {
return new PIso<>(Function1.identity(), Function1.identity());
}
public PIso reverse() {
return new PIso<>(reverseGet, get);
}
public A get(S target) {
return get.apply(target);
}
public T set(B value) {
return reverseGet.apply(value);
}
public T modify(S target, Function1 mapper) {
return lift(mapper).apply(target);
}
public Function1 lift(Function1 mapper) {
return mapper.compose(get).andThen(reverseGet)::apply;
}
public PLens asLens() {
return PLens.of(this.get, (target, value) -> this.set(value));
}
public PPrism asPrism() {
return PPrism.of(this.get.andThen(Either::right), reverseGet);
}
public POptional asOptional() {
return POptional.of((target, value) -> this.set(value), this.get.andThen(Either::right));
}
public PIso compose(PIso other) {
return new PIso<>(
this.get.andThen(other.get),
this.reverseGet.compose(other.reverseGet));
}
public PLens compose(PLens other) {
return asLens().compose(other);
}
public PPrism compose(PPrism other) {
return asPrism().compose(other);
}
public POptional compose(POptional other) {
return asOptional().compose(other);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy