Skip to content

Commit 31ad726

Browse files
authored
Add These::fromMaybes (palatable#117)
1 parent 7af1b9c commit 31ad726

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/main/java/com/jnape/palatable/lambda/adt/These.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,25 @@ public static <A, B> These<A, B> both(A a, B b) {
189189
return new Both<>(tuple(a, b));
190190
}
191191

192+
/**
193+
* Convenience method for converting a pair of {@link Maybe}s into a {@link Maybe} of {@link These}. If both
194+
* {@link Maybe}s are {@link Maybe#just} then the result is a {@link Maybe#just} {@link These#both}. If only one
195+
* {@link Maybe} is {@link Maybe#just} then it will be {@link Maybe#just} {@link These#a} or
196+
* {@link Maybe#just} {@link These#b}. If both {@link Maybe}s are {@link Maybe#nothing} then the result will be
197+
* {@link Maybe#nothing}.
198+
*
199+
* @param maybeA the first optional value
200+
* @param maybeB the second optional value
201+
* @param <A> the first possible type
202+
* @param <B> the second possible type
203+
* @return the wrapped values as a <code>{@link Maybe}&lt;{@link These}&lt;A,B&gt;&gt;</code>
204+
*/
205+
public static <A, B> Maybe<These<A, B>> fromMaybes(Maybe<A> maybeA, Maybe<B> maybeB) {
206+
return maybeA.fmap(a -> maybeB.fmap(b -> both(a, b)).orElse(a(a)))
207+
.fmap(Maybe::just)
208+
.orElse(maybeB.fmap(These::b));
209+
}
210+
192211
/**
193212
* The canonical {@link Pure} instance for {@link These}.
194213
*

src/test/java/com/jnape/palatable/lambda/adt/TheseTest.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,12 @@
1212
import testsupport.traits.MonadRecLaws;
1313
import testsupport.traits.TraversableLaws;
1414

15+
import static com.jnape.palatable.lambda.adt.Maybe.just;
16+
import static com.jnape.palatable.lambda.adt.Maybe.nothing;
1517
import static com.jnape.palatable.lambda.adt.These.a;
1618
import static com.jnape.palatable.lambda.adt.These.b;
1719
import static com.jnape.palatable.lambda.adt.These.both;
20+
import static com.jnape.palatable.lambda.adt.These.fromMaybes;
1821
import static com.jnape.palatable.lambda.functor.builtin.Lazy.lazy;
1922
import static com.jnape.palatable.traitor.framework.Subjects.subjects;
2023
import static org.junit.Assert.assertEquals;
@@ -48,4 +51,12 @@ public void staticPure() {
4851
These<String, Integer> these = These.<String>pureThese().apply(1);
4952
assertEquals(b(1), these);
5053
}
54+
55+
@Test
56+
public void fromMaybesPermutations() {
57+
assertEquals(nothing(), fromMaybes(nothing(), nothing()));
58+
assertEquals(just(These.a(1)), fromMaybes(just(1), nothing()));
59+
assertEquals(just(These.b(1)), fromMaybes(nothing(), just(1)));
60+
assertEquals(just(These.both(1, "hello")), fromMaybes(just(1), just("hello")));
61+
}
5162
}

0 commit comments

Comments
 (0)