Created
August 21, 2022 14:48
-
-
Save gabrieljones/8a36a9ef0a565ede142a530e755fc2d1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package dev.gabrieljones; | |
import io.vavr.control.Either; | |
import io.vavr.control.Option; | |
import io.vavr.control.Try; | |
import java.util.Optional; | |
import java.util.function.Consumer; | |
import java.util.function.Function; | |
import java.util.function.Supplier; | |
public interface Unit { | |
Void voidUnit = null; | |
interface Thunk { void apply(); } | |
static <T> Function<T, Void> voidFunction(Consumer<? super T> consumer) { | |
return t -> { | |
consumer.accept(t); | |
return voidUnit; | |
}; | |
} | |
static <T> Function<T, Void> voidFunction() { | |
return t -> voidUnit; | |
} | |
static <R> Supplier<Void> voidSupplier(Supplier<? super R> supplier) { | |
return () -> { | |
supplier.get(); | |
return voidUnit; | |
}; | |
} | |
static Supplier<Void> voidSupplier(Thunk thunk) { | |
return () -> { | |
thunk.apply(); | |
return voidUnit; | |
}; | |
} | |
static Supplier<Void> voidSupplier() { | |
return () -> voidUnit; | |
} | |
static <T> void fold( | |
Optional<? extends T> foldable, | |
Thunk ifNone, | |
Consumer<? super T> f | |
) { | |
if (foldable.isEmpty()) { ifNone.apply(); } else { f.accept(foldable.get()); } | |
} | |
static <T> void fold( | |
Option<? extends T> foldable, | |
Thunk ifNone, | |
Consumer<? super T> f | |
) { | |
foldable.fold( | |
voidSupplier(ifNone), | |
voidFunction(f) | |
); | |
} | |
static <T> void fold( | |
Try<? extends T> foldable, | |
Consumer<? super Throwable> ifFailure, | |
Consumer<? super T> f | |
) { | |
foldable.fold( | |
voidFunction(ifFailure), | |
voidFunction(f) | |
); | |
} | |
static <L, R> void fold( | |
Either<? extends L, ? extends R> foldable, | |
Consumer<? super L> fL, | |
Consumer<? super R> fR | |
) { | |
foldable.fold( | |
voidFunction(fL), | |
voidFunction(fR) | |
); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package dev.gabrieljones; | |
import java.util.Optional; | |
public class UnitTest { | |
public static void main(String[] args) { | |
Unit.fold( | |
Optional.empty(), | |
() -> System.out.println("Empty"), | |
System.out::println | |
); | |
Unit.fold( | |
Optional.ofNullable(null), | |
() -> System.out.println("Empty"), | |
System.out::println | |
); | |
Unit.fold( | |
Optional.of(42), | |
() -> System.out.println("Empty"), | |
System.out::println | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment