Guest User

Untitled

a guest
Jun 19th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. final Function<String, Integer> length = str -> str.length();
  2. final var lengthOfFoo = length.apply("foo");
  3.  
  4. // not correct! But most functional libraries also supply those for convenience
  5. final BiFunction<String, String, Integer> length2 = (str1, str2) -> str1.length() + str2.length();
  6. final var lengthOfFooAndBar = length2.apply("foo", "bar");
  7.  
  8. // curried form of the above "convenient" form (compact)
  9. final Function<String, Function<String, Integer> length2Curried = str1 -> str2 -> str1.length() + str2.length();
  10. // the above function can also be written more verbosely as:
  11. final Function<String, Function<String, Integer> length2Curried = str1 -> {
  12. // the return value is Function<String, Integer>
  13. // the context (str1) has been "closed over" in the returned function <- this is called a closure
  14. return str2 -> str1.length() + str2.length();
  15. }
  16. final var lengthOfFooAndBar = length2Curried.apply("foo").apply("bar");
  17.  
  18. // partially applied function
  19. final Function<String, Int> plusLengthFoo = length2Curried.apply("foo");
  20. final var lengthOfFooAndBar = plusLengthFoo.apply("bar");
  21.  
  22. // partial function: is not defined for divisor == 0
  23. // this is slightly more involved, but I wanted to supply one possible implementation for completeness
  24. // We will get to what Option is and how one could implement this in a slightly more "functional" way
  25. final Function<Integer, Function<Integer, Option<Integer>>> divisionByN = divisor -> dividend -> {
  26. if (divisor == 0)
  27. return None();
  28. return Some(dividend / divisor);
  29. }
Add Comment
Please, Sign In to add comment