Functional Programming in Java

Getting Started

Created by Mark Perry, @mprry, G+, Blog, LinkedIn, GitHub, maperry78@yahoo.com.au

Goals

  • Write programs by combining pure functions
  • Learn by immersion with examples
  • Higher order functions

Example

  • See GettingStarted.java
  • Effect pushed to outer shell
  • Program is RT, since main is not called from program
  • Note immutable values

Loops


// imperative factorial
static int factorial(int n) {
    int i = n;
    int result = 1;
    while (i > 1) {
        result = result * i;
        i = i - 1;
    }
    return result;
}
                    

Polymorphic Functions

  • Previously monomorphic
  • Abstract over any type
  • Takes a list of type parameters/variables

static <A> boolean isSorted(List<A> as, F2<A, A, Boolean> f) {...}

static <A, B> B fold(List<A> as, F2<B, A, B> f, B b) {...}

static <A, B, C> F<B, C> partial1(A a, F2<A, B, C> f) {...}

static <A, B, C> F<A, F<B, C>> curry(F2<A, B, C> f) {...}

static <A, B, C> F<A, C> andThen(F<A, B> f, F<B, C> g) {...}
					

Summary

  • Learn basic FP concepts
  • Some simple Java
  • Recursion
  • Higher Order Functions
  • Polymorphism

Afterword

Functional Programming in Scala, Chiusano and Bjarnason, Chapter 2, Getting Started

Created by Mark Perry, @mprry, G+, Blog, LinkedIn, GitHub, maperry78@yahoo.com.au