25
Functional Programming @bruno_lui

Functional Programming

Embed Size (px)

Citation preview

Functional Programming

@bruno_lui

Imperative programming paradigm

is about . . .

modifying mutable variables

using assignments

and control structures such as if, then, else, lops, break,

continue, return

Functional programming paradigm

means ...

modifying mutable variables

assignments

programming without

and other imperative control structures

programming focusing on the functions

functions ARE values that can be produced, consumed

and composed

Principles and

Concepts

Immutable Data

Functional programs should be immutable, which means you would simply create new

data structures instead of modifying ones that already exist.

Referential transparency

Functional programs should perform every task as if for the first time, with no knowledge of what

may or may not have happened earlier in the program’s execution and without side effects.

Function as first-class citizens

functions can be defined anywhere

they can be passed as parameters to functions and returned as results

there exists a set of operators to compose functions

• A number can be stored in a variable and so can a function:

var fortytwo = function() { return 42 };

• A number can be stored in an array slot and so can a function:

var fortytwos = [42, function() { return 42 }];

• A number can be stored in an object field and so can a function:

var fortytwos = {number: 42, fun: function() { return 42 }};

• A number can be created as needed and so can a function:

42 + (function() { return 42 })(); //=> 84

• A number can be passed to a function and so can a function:

function weirdAdd(n, f) { return n + f() } weirdAdd(42, function() { return 42 }); //=> 84

• A number can be returned from a function and so can a function:

return 42; return function() { return 42 };

Composing Functions

In functional programming, you’re always looking for simple, repeatable actions to be

abstracted out into a function.

We can then build more complex features by calling these functions in sequence

"Functional programming is the use of functions that transform values into units of abstraction, subsequently used to build software systems."

code examples

Give a 10% discount to all products of the chart above $30

Show the total value of products and discount

Imperative

Double valorTotal = 0d;Double descontoTotal = 0d;for (Produto produto : produtos) { valorTotal += produto.getValor(); if (produto.getValor() > 30.00) { descontoTotal += produto.getValor() * 0.1; }}valorTotal -= descontoTotal;

functional

val valores = produtos map (_.valor)val valorTotal = valores reduce ((total, valor) => total + valor)

val descontoTotal = valores filter (_ > 30.00) map (_ * 0.10) reduce ((total, desconto) => total + desconto)

val total = valorTotal - descontoTotal

code examples

Write a program to build a lyric sheet for

the song “99 bottles of beer"

X bottles of beer on the wall

X bottles of beer

Take one down, pass it around

X-1 bottles of beer on the wall

No more bottles of beer on the wall

Imperativevar lyrics = [];

for (var bottles = 99; bottles > 0; bottles--) { lyrics.push(bottles + " bottles of beer on the wall”);lyrics.push(bottles + " bottles of beer"); lyrics.push("Take one down, pass it around");

if (bottles > 1) { lyrics.push((bottles - 1) + " bottles of beer on the wall.");

} else { lyrics.push("No more bottles of beer on the wall!”);

}}

functional

function lyricSegment(n) { return _.chain([]) .push(n + " bottles of beer on the wall") .push(n + " bottles of beer”).push("Take one down, pass it around") .tap(function(lyrics) {

if (n > 1) lyrics.push((n - 1) + " bottles of beer on the wall.");

else lyrics.push("No more bottles of beer on the wall!");

}).value();

}

functional

lyricSegment(9);

//=> ["9 bottles of beer on the wall", // "9 bottles of beer", // "Take one down, pass it around", // "8 bottles of beer on the wall."]

functional

function song(start, end, lyricGen) { return _.reduce(_.range(start,end,-1),

function(acc,n) { return acc.concat(lyricGen(n)); }, []);

}

And using it is as simple as: song(99, 0, lyricSegment); //=> ["99 bottles of beer on the wall",// ...// "No more bottles of beer on the wall!"]

1. All of your functions must accept at least one argument.

2. All of your functions must return data or another function.

3. No loops

3 simple rules to avoid imperative habits

conclusions

data abstractions

composing functions

declarative programming

concise code

Coursera: Functional Programming Principles in Scala

Book: Functional Javascript, Michael Fogus

http://www.smashingmagazine.com/2014/07/02/dont-be-scared-of-functional-programming/

References

Thank you

@bruno_lui