Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- final Function<String, Integer> length = str -> str.length();
- final var lengthOfFoo = length.apply("foo");
- // not correct! But most functional libraries also supply those for convenience
- final BiFunction<String, String, Integer> length2 = (str1, str2) -> str1.length() + str2.length();
- final var lengthOfFooAndBar = length2.apply("foo", "bar");
- // curried form of the above "convenient" form (compact)
- final Function<String, Function<String, Integer> length2Curried = str1 -> str2 -> str1.length() + str2.length();
- // the above function can also be written more verbosely as:
- final Function<String, Function<String, Integer> length2Curried = str1 -> {
- // the return value is Function<String, Integer>
- // the context (str1) has been "closed over" in the returned function <- this is called a closure
- return str2 -> str1.length() + str2.length();
- }
- final var lengthOfFooAndBar = length2Curried.apply("foo").apply("bar");
- // partially applied function
- final Function<String, Int> plusLengthFoo = length2Curried.apply("foo");
- final var lengthOfFooAndBar = plusLengthFoo.apply("bar");
- // partial function: is not defined for divisor == 0
- // this is slightly more involved, but I wanted to supply one possible implementation for completeness
- // We will get to what Option is and how one could implement this in a slightly more "functional" way
- final Function<Integer, Function<Integer, Option<Integer>>> divisionByN = divisor -> dividend -> {
- if (divisor == 0)
- return None();
- return Some(dividend / divisor);
- }
Add Comment
Please, Sign In to add comment