Skip to content

Commit 1271ab7

Browse files
t-rutten7h3kk1d
andcommitted
Function is applicative
Co-authored-by: Alexander Bandukwala <[email protected]>
1 parent 5390efb commit 1271ab7

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

src/test/java/com/jnape/palatable/lambdakoans/AboutApplicatives.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@
22

33
import com.jnape.palatable.lambda.adt.Either;
44
import com.jnape.palatable.lambda.adt.Maybe;
5+
import com.jnape.palatable.lambda.adt.hlist.Tuple2;
56
import com.jnape.palatable.lambda.functions.Fn1;
7+
import com.jnape.palatable.lambda.functions.Fn3;
8+
import com.jnape.palatable.lambda.functions.builtin.fn3.LiftA2;
9+
import com.jnape.palatable.lambda.functions.builtin.fn4.LiftA3;
610
import com.jnape.palatable.lambda.functor.Applicative;
711
import com.jnape.palatable.lambda.functor.builtin.Lazy;
812
import com.jnape.palatable.lambda.traversable.LambdaIterable;
@@ -14,6 +18,7 @@
1418
import static com.jnape.palatable.lambda.adt.Either.right;
1519
import static com.jnape.palatable.lambda.adt.Maybe.just;
1620
import static com.jnape.palatable.lambda.adt.Maybe.nothing;
21+
import static com.jnape.palatable.lambda.adt.hlist.HList.tuple;
1722
import static com.jnape.palatable.lambda.functions.Fn1.fn1;
1823
import static com.jnape.palatable.lambda.functions.builtin.fn1.Repeat.repeat;
1924
import static com.jnape.palatable.lambda.functions.builtin.fn2.Take.take;
@@ -88,4 +93,28 @@ public void lazyApplicatives() {
8893
assertThat(nothingToString, equalTo(nothing()));
8994
assertThat(computed.get(), equalTo(100_000));
9095
}
96+
97+
@Test
98+
public void functionIsApplicative() {
99+
Fn1<String, Integer> strLen = String::length;
100+
Fn1<String, String> toUpper = String::toUpperCase;
101+
102+
// Result of unary function calls are passed to mapping function as arguments
103+
Fn1<String, Tuple2<Integer, String>> lengthAndUppercase = LiftA2.liftA2(Tuple2::tuple, strLen, toUpper);
104+
assertThat(lengthAndUppercase.apply("hello world"), equalTo(tuple(11, "HELLO WORLD")));
105+
106+
Fn1<Integer, Integer> mod3 = i -> i % 3;
107+
Fn1<Integer, Integer> div3 = i -> i / 3;
108+
109+
Fn1<Integer, String> showDivision = LiftA2.liftA2((divided, remainder) -> String.format("%d * 3 + %d", divided, remainder), div3, mod3);
110+
assertThat(showDivision.apply(10), equalTo("3 * 3 + 1"));
111+
112+
113+
Fn1<String, Integer> findStart = s -> s.indexOf('j');
114+
Fn1<String, Integer> findEnd = s -> s.indexOf(' ');
115+
Fn3<String, Integer, Integer, String> cutString = String::substring;
116+
117+
Fn1<String, String> transformAndCut = LiftA3.liftA3(cutString, toUpper, findStart, findEnd);
118+
assertThat(transformAndCut.apply("hellojava world"), equalTo("JAVA"));
119+
}
91120
}

0 commit comments

Comments
 (0)