jabrena / ReactiveLab

A Lab about reactive technologies with Java 8 to be applied on Backend.
https://jabrena.github.io/ReactiveLab/www/
MIT License
1 stars 0 forks source link

Add contents for Game 3 #7

Open jabrena opened 7 years ago

jabrena commented 7 years ago

Functional Programming is a concept which treats functions as first class citizens. At the core of functional programming is immutability. It emphasizes on application of functions in contrast to imperative programming style which emphasizes on change in state. https://www.jcp.org/aboutJava/communityprocess/final/jsr335/index.html

Exercises:

https://rosettacode.org/wiki/Rosetta_Code http://www.learntosolveit.com/#java-programming-language https://www.lucidchart.com/techblog/2016/11/22/tracking-data-in-complex-java-code-a-functional-programming-approach/ https://pawelwlodarski.gitbooks.io/functional-programming/content/functions_in_java_-_intro.html https://github.com/PawelWlodarski/workshops-javafp https://pawelwlodarski.gitbooks.io/functional-programming/content/workshop1.html

jabrena commented 7 years ago

Books:

https://www.amazon.com/Java-Lambdas-Functional-Programming-Masses/dp/1449370772/ref=pd_sbs_14_t_1?_encoding=UTF8&psc=1&refRID=A30BPKCB6D60170A57R5 https://www.amazon.com/Mastering-Lambdas-Programming-Multicore-Oracle/dp/0071829628/ref=pd_sbs_14_t_2?_encoding=UTF8&psc=1&refRID=A30BPKCB6D60170A57R5 https://www.amazon.co.uk/Functional-Programming-Java-Harnessing-Expressions/dp/1937785467 https://www.manning.com/books/functional-programming-in-java https://pragprog.com/book/vsjava8/functional-programming-in-java

jabrena commented 7 years ago

Articles:

http://blog.smartbear.com/programming/7-silly-programming-challenges-to-do-for-fun/ http://www.vasinov.com/blog/16-months-of-functional-programming https://blog.javathlon.com/functional-programming-in-java-8-series-i-a8452fdf81e#.yz2pd326z http://viralpatel.net/blogs/lambda-expressions-java-tutorial/ https://dzone.com/articles/why-we-need-lambda-expressions-0 https://dzone.com/articles/functional-programming-java-8 http://www.drdobbs.com/jvm/lambda-expressions-in-java-8/240166764 https://en.wikipedia.org/wiki/Higher-order_programming https://en.wikipedia.org/wiki/Currying https://www.javacodegeeks.com/2014/03/functional-programming-with-java-8-lambda-expressions-monads.html https://dzone.com/articles/whats-wrong-java-8-part-iii https://dzone.com/articles/whats-wrong-java-8-part-ii https://dzone.com/articles/whats-wrong-java-8-currying-vs http://www.beyondjava.net/blog/java-8-functional-programming-language/ https://jlordiales.me/2014/11/01/overview-java-8/ http://es.slideshare.net/LivePersonDev/functional-programming-with-java-8 https://dzone.com/articles/why-we-need-lambda-expressions-0

jabrena commented 7 years ago

https://kirbyfan64.github.io/posts/functional-programming-isnt-the-answer-to-all-problems-and-neither-is-oop.html https://dzone.com/articles/functional-programming-jvm https://www.quora.com/When-is-OOP-better-than-FP-and-vice-versa https://pysaumont.github.io/#blog

jabrena commented 7 years ago

http://www.nurkiewicz.com/2016/06/functor-and-monad-examples-in-plain-java.html?m=1

jabrena commented 7 years ago

https://github.com/jabrena/parallel-streams-example

jabrena commented 7 years ago

Examples: http://examples.oreilly.com/0636920021667/

jabrena commented 7 years ago

https://docs.oracle.com/javase/8/docs/api/java/util/function/Function.html

jabrena commented 7 years ago
package math;

public class Factorial {

  public static long declarativeFactorial(int n) {
    assert n > 0 : "Argument must be greater than 0";
    if (n == 1) return 1;
    else return n * declarativeFactorial(n-1);
  }

  public static long imperativeFactorial(int n) {
    assert n > 0 : "Argument must be greater than 0";
    long result = 1;
    for (int i = 2; i<= n; i++) {
      result *= i;
    }
    return result;
  }
}
jabrena commented 7 years ago

https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html

jabrena commented 7 years ago

The Basic Principles of Functional Programming Avoiding Mutable State Functions as First-Class Values

public interface Function1Void { void apply(A a); }

Lambdas and Closures Function1Void

public interface Function2<A1, A2, R> { R apply(A1 a1, A2 a2); }

A closure is formed when the body of a function refers to one or more free variables, variables that aren’t passed in as arguments or defined locally, but are defined in the enclosing scope where the function is defined. The runtime has to “close over” those variables so they are available when the function is actually executed, which could happen long after the original variables have gone out of scope! Java has limited support for closures in inner classes; they can only refer to final variables in the enclosing scope.

Higher-Order Functions Side-Effect-Free Functions Recursion

package functions; import static org.junit.Assert.*; import org.junit.Test; public class RecursionTest { static class Tree { // public fields for simplicity public final Tree left; // left subtree public final Tree right; // right subtree public final int value; // value at this node public Tree(Tree left, int value, Tree right) { this.left = left; this.value = value; this.right = right; } public final String toString() { String leftStr = left == null ? "^" : left.toString(); String rightStr = right == null ? "^" : right.toString(); return "(" + leftStr + "-" + value + "-" + rightStr + ")"; } } @Test public void walkATree() { Tree root = new Tree( new Tree( new Tree(null, 3, null), 2, new Tree(new Tree(null, 5, null), 4, null)), 1, new Tree( new Tree(null, 7, null), 6, new Tree(null, 8, null))); String expected = "(((^-3-^)-2-((^-5-^)-4-^))-1-((^-7-^)-6-(^-8-^)))"; assertEquals(expected, root.toString()); }

Lazy vs. Eager Evaluation Declarative vs. Imperative Programming

public abstract class Option { public abstract boolean hasValue(); public abstract T get(); public T getOrElse(T alternative) { return hasValue() == true ? get() : alternative; } }

jabrena commented 7 years ago

Exercises:

  1. Write unit tests for Function1Void and Function2.
  2. Write a method that uses recursion to add a list of numbers.
  3. Find some Java code you wrote before that does null checks. Try modifying it to use Option instead.
jabrena commented 7 years ago

Pure functional programming uses recursion instead of loops, since a loop counter would have to be mutable.

jabrena commented 7 years ago

Exercises

  1. Add a factory method to ListModule that takes a variable argument list of elements and returns a properly constructed list.
  2. Implement a new ListModule where head and tail return Options. This eliminates the slight smell of throwing exceptions for the empty list case. However, using Options makes some other code more awkward, as a unit test will show.
  3. Re-implement the Option hierarchy following the idioms used for List; e.g., make None a static constant.
  4. Implement a MapModule with an abstract data type Map. The implementation classes should use side-effect-free functions and immutability. How can you enable the use of alternative implementations that optimize performance and memory usage? What implementations would optimize the following: a. A map that contains just a few key-value pairs. b. A map that contains a few million key-value pairs. c. A map that optimizes insertion performance. d. A map that optimizes search performance. e. A map that retains the order of insertion (e.g., for subsequent traversal).
  5. ForeachExample prints the arguments in reverse order. Determine the cause and implement a fix. Hint: consider adding a useful method to ListHelper that is commonly found in List classes.
  6. Reimplement the equals and toString methods in NonEmptyList using foldLeft or foldRight. Does the choice of fold method affect the results?
  7. Reimplement the filter and map methods for Lists using foldLeft or foldRight.
  8. Reimplement foldLeft and foldRight so they don’t use recursion. If you use mutable values, preserve thread safety.
jabrena commented 7 years ago

We’ve seen other reasons to avoid mutability. Mutable objects are not thread-safe by default and it’s easy for clients to change their state outside our control. Hence, we should make our objects immutable by removing setter methods and by declaring fields final.

jabrena commented 7 years ago

Sometimes we can’t avoid mutation. Since Java doesn’t perform tail-call optimization, declarativeFactorial won’t perform as well as imperativeFactorial. However, we should choose the desirable approach first, then optimize only where actual performance data says we should (since our intuitions are seldom correct). If at all possible, we should keep all public abstractions pure, even when the internals aren’t pure.

jabrena commented 7 years ago

The Liskov Substitution Principle The Liskov Substitution Principle (LSP; see [LSP] and [Martin2003]) provides the correct way to think about subtyping. Paraphrasing, LSP says that if you have an object of type T1 with a set of properties, you can only substitute an object of type T2 if it also conforms to those properties. We say that T2 is a subtype of T1. In Java, a child class that derives from a parent class is considered a subtype. Subtyping, Inheritance, and Polymorphism We sometimes think of subtyping and inheritance as the same thing. Inheritance is used for subtype polymorphism, where we define type hierarchies with polymorphic behavior. Inheritance is also sometimes used for implementation inheritance, a form of reuse, which can cause problems with Liskov substitutability. For completeness, note that Java’s generics are an example of parametric polymorphism. For example, a List should behave the same whether T is String, Float, etc. A practical way to ensure that LSP is satisfied is to use Design by Contract [Meyer1997], where you specify allowed properties as one of three kinds of constraints at the level of individual functions or whole types: • Precondition: A condition that must be true when entering the function (or all functions for a type-level precondition). Example: Input parameter x can’t be null. • Postcondition: A condition that must be true when leaving the function (or all functions for a type-level postcondition). Example: The return value will never be null. • Invariant: A condition that must be true both before and after the function call (or all functions). Example: Field f will never be null.

jabrena commented 7 years ago

http://www.java2s.com/Tutorials/Java/java.util.function/Function/1020__Function.apply.htm https://www.pgrs.net/2015/04/23/partial-function-application-in-java-8/ http://www.javabrahman.com/java-8/java-8-java-util-function-function-tutorial-with-examples/

jabrena commented 7 years ago

https://github.com/oreillymedia/functional_thinking

jabrena commented 7 years ago

Concept 1: Lambda & Functional interface https://dzone.com/articles/introduction-functional-1 http://www.javaworld.com/article/2092260/java-se/java-programming-with-lambda-expressions.html?page=2 https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

jabrena commented 7 years ago

Exercises

  1. Find some Java code you wrote before that does null checks. Try modifying it to use Option instead.
jabrena commented 7 years ago

http://blog.codefx.org/java/dev/design-optional/

jabrena commented 7 years ago

https://bitbucket.org/atlassian/fugue/src/0f6a9923dd38888437ca87ec82089c548d9b3a5f/fugue/src/main/java/io/atlassian/fugue/?at=master