Functional Programming

Functioning Program

Functioning Program

Functional Programming

What is a Function?

Functional Programming?

a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathmatical functions and avoids changing-state and mutable data

Key Takeaway

NO SIDE EFFECTS!

var x = 2;

function square(){
    x = x * x;
}
var x = 2;

console.log(x) // 2

function square(){
    x = x * x;
}

square();

console.log(x); // 4

NOT FUNCTIONAL!

How do we make this functional?

var x = 2;

function square(y: number){
    return y * y;
}
var x = 2;

console.log(x) // 2

function square(y: number){
    return y * y;
}

square(x);

console.log(x); // 2

Other characteristics of functional programming...

Functions are first class

can be passed, returned, assigned, etc.. 

var square = function(x) {
    return x * x;
}
setTimeout(function(){
    console.log('A function 
        can be passed as an argument');
}, 1000);

Data is immutable

State cannot change after creation

Random Fun Fact

Entscheidungsproblem

What are some functional languages?

Is Java Functional?

Can we apply some of these concepts...?

Java 8 introduced lamda's and streams

Simple Lamda Expression

(x, y) -> x + y;
int add(int x, int y) {
    return x + y;
}
List<String> names = 
    Arrays.asList("Joe", "Jack", "James");

Print the names to the console...?

for (String name : names) {
    System.out.println(name);
}

How to do this using lamda's...?

names.forEach(name -> System.out.println(name));
function(name){
    System.out.println(name);
}
Map<String,Integer> map = new HashMap<>();
map.put("Atlanta, Georgia", 110);
map.put("Austin, Texas", 115);
map.put("Baltimore, Maryland", 105);
map.put("Birmingham, Alabama", 99);
map.put("Boston, Massachusetts", 98);
for (Map.Entry<String,Integer> e : map.entrySet()) {
    System.out.println(e.getKey() + " => " + 
        e.getValue());
}
map.forEach((k, v) -> System.out.println(k + " => " + v));

Java 8 Streams

  • start with 'c'

  • change 'c' to 'C'

  • sorted

  • print

List<String> myList =
    Arrays.asList("a1", "a2", "b1", "c2", "c1");
List<String> myList =
    Arrays.asList("a1", "a2", "b1", "c2", "c1");

myList
    .stream()
    .filter(s -> s.startsWith("c"))
    .map(String::toUpperCase)
    .sorted()
    .forEach(System.out::println);

// C1
// C2

Why Functional?

Easier to understand

Unit Test

Write less code

Questions?