26
Functional Programming 101 An introduction to functional programming

Functional programming 101

Embed Size (px)

Citation preview

Functional Programming 101An introduction to functional programming

Who am I?● Marcle Rodrigues● Software Developer @Codeminer42● @Maarclee● @marcle.rodrigues

Agenda● Caveats● Introduction● First-Class Functions● Function Composition● Higher-Order Functions● Currying● Purity● Immutability● Recursion

Caveats● Things will be very different● What you know will not translate● Change the way that you think

Forget everything you know

Learning FP takes a while. Be Patient

Introduction

Functional Programming

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

First Class Citizen

Higher Order Functions

Higher Order Functionsdefmodule Tripler do

def tripler(value, function) do

3 * function.(value)

end

end

Currying

Purity

Pure Functions● Only operate on their input params● Will always produce the same output given the

same inputs● No side effects

Side Effects● FP doesn’t eliminate side effects● Some parts of every program must be impure● Our goal:

– Minimize the amount of impure code and segregate it from the rest of out program.

Is it pure?

defmodule Math do

def add(x, y) do

x + y

end

end

Immutability

var x = 1;

x = x + 1;

Immutability● There are no variables in Functional Programming● Stored values● While alive, x can never change● Multi-valued changes● Single-valued changes● Recursion● Multi-thread safety

Recursiondefmodule Math do

def sum_list([head | tail], accumulator) do

sum_list(tail, head + accumulator)

end

def sum_list([], accumulator) do

accumulator

end

end

Why Global Mutable State is so bad?

Immutability creates simpler and safer code

That’s all, Folks!

Estamos [email protected]@gmail.com