Lessons of Functional programming

Author: Vassil Dichev
Date: 12.09.2015

Who am I?

Why learn?

Development is moving towards functional programming

...or is, at least, increasingly influenced by it.

Great paradigm shifts

Benefits

Structured programming

Garbage collection

Function definition

Definitions of FP

Finding FP

Side effects- first lesson

PROCEDURE ToFahrenheit(x: REAL);
BEGIN
  WriteLn(9/5 * x + 32);
END

FUNCTION ToFahrenheit(x: REAL): REAL;
BEGIN
  ToFahrenheit := 9/5 * x + 32;
END

Side effects- first lesson

public static void fahrenheit(double c) {
    out.println(1.8 * c + 32);
}
public static double fahrenheit(double c) {
    return 1.8 * c + 32;
}

Referential transparency

Benefits

Immutability

Java Concurrency

Immutable objects are simple.

Immutable objects are also safer.

Immutable objects are always thread-safe.

Immutability

Benefits

HDYWTDT?

i = 1
i = 2

Multiple declarations of `i'
i = 1
i = 2

exception error: no match of right
  hand side value 2

Life without mutation

Iterative factorial

public static long factorial(int num) {
    long result = 1;
    for(int i = 2; i <= num; i++) {
        result *= i;
    }
    return result;
}

Recursive factorial

public static long factorial(int num) {
    if (num == 0) {
        return 1;
    } else {
        return num * factorial(num - 1);
    }
}

Recursion and the stack

images/stack.jpg

Functional data structures

images/list.jpg

Git graph

images/git-graph.jpg

Variable capture

Must be effectively final

int sum = 0;
list.forEach(e -> { sum += e.size(); });

Race conditions

To evolve the language in 2011 in a way that makes concurrent and parallel operations even more dangerous would be foolish.

—Brian Goetz

Higher-order functions

Functions, which take other functions as parameters and/or return functions.

  • map (collect)
images/map_op.jpg
  • filter (select, find_all, findAll)
images/filter_op.jpg
  • fold (reduce, inject)
images/fold_op.jpg

Combinators are reusable!

Higher-order functions are also called combinators

Combinators are arguably the most reusable constructs we have in programming

—Dean Wampler

images/fp4jd.jpg

New idioms

list.map(e -> e.size())
    .reduce(0, (a, b) -> a+b);

SQL and higher-order functions

SELECT age, name from PEOPLE where age > 18
people.filter(_.age > 18).
       map(p => (p.age, p.name))

Expressions everywhere

Patterns are FP

Languages

map (2 *) [1, 2, 3]
filter even [1, 2, 3]
map(fun(X) -> 2 * X end, [1,2,3]).
filter(fun(X) -> X rem 2 == 0 end, [1,2,3]).

JVM languages

list.map(2 * _)
list.filter(_ % 2 == 0)
(map #(* 2 %) '(1 2 3))
(filter #(= (mod % 2) 0) '(1 2 3))

Java libraries

Summary

The End