From 44be6e6cd7671dd243056107ffa6201504f7fbce Mon Sep 17 00:00:00 2001 From: Ben Culkin Date: Sun, 25 Jun 2023 15:50:38 -0400 Subject: Update a number of things --- src/main/java/bjc/optics/AdapterX.java | 89 ++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 src/main/java/bjc/optics/AdapterX.java (limited to 'src/main/java/bjc/optics/AdapterX.java') diff --git a/src/main/java/bjc/optics/AdapterX.java b/src/main/java/bjc/optics/AdapterX.java new file mode 100644 index 0000000..f037508 --- /dev/null +++ b/src/main/java/bjc/optics/AdapterX.java @@ -0,0 +1,89 @@ +/* + * 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); + } +} -- cgit v1.2.3