/*
* esodata - data structures of varying utility
*
* Copyright 2022, Ben Culkin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
package bjc.optics;
import java.util.function.Function;
/**
* An adapter that maps between two sets of types
*
* @author bjcul
*
* @param The type of the first source
* @param The type of the second source
* @param The type of the first destination
* @param The type of the second destination
*/
public interface AdapterX extends Optic {
/**
* Create a source from a destination
*
* @param source The destination to use
*
* @return A source corresponding to the destination
*/
F1 from(T1 source);
/**
* Create a destination from a source
*
* @param source The source to use
*
* @return A destination corresponding to the source
*/
T2 to(F2 source);
/**
* Create an adapter from its component parts
*
* @param The type of the first source
* @param The type of the second source
* @param The type of the first destination
* @param The type of the second destination
*
* @param f The 'from' function
* @param g The 'to' function
*
* @return The adapter constructed from the given parts.
*/
public static AdapterX of(Function f, Function g) {
return new FunctionalAdapterX<>(f, g);
}
}
final class FunctionalAdapterX implements AdapterX {
private final Function f;
private final Function g;
public FunctionalAdapterX(Function f, Function g) {
this.f = f;
this.g = g;
}
@Override
public W1 from(P1 source) {
return f.apply(source);
}
@Override
public P2 to(W2 source) {
return g.apply(source);
}
}