|
| 1 | +package com.jnape.palatable.lambda.functions.builtin.fn2; |
| 2 | + |
| 3 | +import com.jnape.palatable.lambda.functions.Fn1; |
| 4 | +import com.jnape.palatable.lambda.functions.Fn2; |
| 5 | + |
| 6 | +/** |
| 7 | + * Function application, represented as a higher-order {@link Fn2} that receives an {@link Fn1} and its argument, and |
| 8 | + * applies it. Useful for treating application as a combinator, e.g.: |
| 9 | + * <pre> |
| 10 | + * {@code |
| 11 | + * List<Fn1<Integer, Integer>> fns = asList(x -> x + 1, x -> x, x -> x - 1); |
| 12 | + * List<Integer> args = asList(0, 1, 2); |
| 13 | + * Iterable<Integer> results = zipWith($(), fns, args); // [1, 1, 1] |
| 14 | + * } |
| 15 | + * </pre> |
| 16 | + * |
| 17 | + * @param <A> the applied {@link Fn1 Fn1's} input type |
| 18 | + * @param <B> the applied {@link Fn1 Fn1's} output type |
| 19 | + */ |
| 20 | +public final class $<A, B> implements Fn2<Fn1<? super A, ? extends B>, A, B> { |
| 21 | + private static final $<?, ?> INSTANCE = new $<>(); |
| 22 | + |
| 23 | + private $() { |
| 24 | + } |
| 25 | + |
| 26 | + @Override |
| 27 | + public B checkedApply(Fn1<? super A, ? extends B> fn, A a) { |
| 28 | + return fn.apply(a); |
| 29 | + } |
| 30 | + |
| 31 | + @SuppressWarnings("unchecked") |
| 32 | + public static <A, B> $<A, B> $() { |
| 33 | + return ($<A, B>) INSTANCE; |
| 34 | + } |
| 35 | + |
| 36 | + public static <A, B> Fn1<A, B> $(Fn1<? super A, ? extends B> fn) { |
| 37 | + return $.<A, B>$().apply(fn); |
| 38 | + } |
| 39 | + |
| 40 | + public static <A, B> B $(Fn1<? super A, ? extends B> fn, A a) { |
| 41 | + return $.<A, B>$(fn).apply(a); |
| 42 | + } |
| 43 | +} |
0 commit comments