SlideShare a Scribd company logo
1 of 67
Download to read offline
+ =f(x)
Functional Go
???
Functional Programming by Wikipidia:
“Functional programming is a programming paradigm that
treats computation as the evaluation of mathematical
functions and avoids state and mutable data". In other
words, functional programming promotes code with no
side effects, no change of value in variables. It
oposes to imperative programming, which emphasizes
change of state”.
What this means?
What this means?
● No mutable data (no side effect).
What this means?
● No mutable data (no side effect).
● No state (no implicit, hidden state).
Once assigned (value binding), a variable (a symbol) does not change its value
What this means?
● No mutable data (no side effect).
● No state (no implicit, hidden state).
Once assigned (value binding), a variable (a symbol) does not change its value.
All state is bad? No, hidden, implicit state is bad.
What this means?
● No mutable data (no side effect).
● No state (no implicit, hidden state).
Once assigned (value binding), a variable (a symbol) does not change its value.
All state is bad? No, hidden, implicit state is bad.
Functional programming do not eliminate state, it just make it visible and explicit
(at least when programmers want it to be).
What this means?
● No mutable data (no side effect).
● No state (no implicit, hidden state).
Once assigned (value binding), a variable (a symbol) does not change its value.
All state is bad? No, hidden, implicit state is bad.
Functional programming do not eliminate state, it just make it visible and explicit
(at least when programmers want it to be).
● Functions are pure functions in the mathematical sense: their output depend only
in their inputs, there is not “environment”.
What this means?
● No mutable data (no side effect).
● No state (no implicit, hidden state).
Once assigned (value binding), a variable (a symbol) does not change its value.
All state is bad? No, hidden, implicit state is bad.
Functional programming do not eliminate state, it just make it visible and explicit
(at least when programmers want it to be).
● Functions are pure functions in the mathematical sense: their output depend only
in their inputs, there is not “environment”.
● Same result returned by functions called with the same inputs.
What are the advantages?
What are the advantages?
● Cleaner code: "variables" are not modified once defined, so we don't have to
follow the change of state to comprehend what a function, a, method, a class, a
whole project works.
What are the advantages?
● Cleaner code: "variables" are not modified once defined, so we don't have to
follow the change of state to comprehend what a function, a, method, a class, a
whole project works.
● Referential transparency: Expressions can be replaced by its values. If we call a
function with the same parameters, we know for sure the output will be the same
(there is no state anywhere that would change it).
What are the advantages?
● Cleaner code: "variables" are not modified once defined, so we don't have to
follow the change of state to comprehend what a function, a, method, a class, a
whole project works.
● Referential transparency: Expressions can be replaced by its values. If we call a
function with the same parameters, we know for sure the output will be the same
(there is no state anywhere that would change it).
There is a reason for which Einstein defined insanity as "doing the same thing over
and over again and expecting different results".
Advantages enabled by referential transparency
Advantages enabled by referential transparency
● Memoization
○ Cache results for previous function calls.
Advantages enabled by referential transparency
● Memoization
○ Cache results for previous function calls.
● Idempotence
○ Same results regardless how many times you call a function.
Advantages enabled by referential transparency
● Memoization
○ Cache results for previous function calls.
● Idempotence
○ Same results regardless how many times you call a function.
● Modularization
○ We have no state that pervades the whole code, so we build our project with
small, black boxes that we tie together, so it promotes bottom-up
programming.
Advantages enabled by referential transparency
● Memoization
○ Cache results for previous function calls.
● Idempotence
○ Same results regardless how many times you call a function.
● Modularization
○ We have no state that pervades the whole code, so we build our project with
small, black boxes that we tie together, so it promotes bottom-up
programming.
● Ease of debugging
○ Functions are isolated, they only depend on their input and their output, so
they are very easy to debug.
Advantages enabled by referential transparency
● Parallelization
○ Functions calls are independent.
○ We can parallelize in different process/CPUs/computers/…
Advantages enabled by referential transparency
● Parallelization
○ Functions calls are independent.
○ We can parallelize in different process/CPUs/computers/…
result = func1(a, b) + func2(a, c)
Advantages enabled by referential transparency
● Parallelization
○ Functions calls are independent.
○ We can parallelize in different process/CPUs/computers/…
We can execute func1 and func2 in parallel because an won’t be modified.
result = func1(a, b) + func2(a, c)
Advantages enabled by referential transparency
● Concurrence
○ With no shared data, concurrence gets a lot simpler:
■ No semaphores.
■ No monitors.
■ No locks.
■ No race-conditions.
■ No dead-locks.
Ok so let's play a little with functional programming?
Don’t Update, Create - String
name := "Geison"
name = name + " Flores"
Don’t Update, Create - String
name := "Geison"
name = name + " Flores"
const firstname = "Geison"
const lastname = "Flores"
const name = firstname + " " + lastname
Don’t Update, Create - Arrays
years := [4]int{2001, 2002}
years[2] = 2003
years[3] = 2004
years // [2001, 2002, 2003, 2004]
Don’t Update, Create - Arrays
years := [4]int{2001, 2002}
years[2] = 2003
years[3] = 2004
years // [2001, 2002, 2003, 2004]
years := []{2001, 2003}
allYears := append(years, []int{2003, 2004}...)
Don’t Update, Create - Maps
ages := map[string]int{"John": 30}
ages["Mary"] = 28
ages // {"John": 30, "Mary": 28}
Don’t Update, Create - Maps
ages := map[string]int{"John": 30}
ages["Mary"] = 28
ages // {"John": 30, "Mary": 28}
ages1 := map[string]int{"John": 30}
ages2 := map[string]int{"Mary": 28}
func mergeMaps(mapA, mapB map[string]int) map[string]int {
allAges := make(map[string]int, len(mapA) + len(mapB))
for k, v := range mapA {
allAges[k] = v
}
for k, v := range mapB {
allAges[k] = v
}
return allAges
}
allAges := mergeMaps(ages1, ages2)
Higher Order Functions
Functions and methods are first-class objects in Golang, so if you want to pass a
function to another function, you can just treat it as any other object.
func caller(f func(string) string) {
result := f("David")
fmt.Println(result)
}
f := func(name string) string {
return "Hello " + name
}
caller(f)
Higher Order Functions - Map
// As Golang do not have a builtin Map implementation, it is possible use this one
// https://github.com/yanatan16/itertools/blob/master/itertools.go
mapper := func (i interface{}) interface{} {
return strings.ToUpper(i.(string))
}
Map(mapper, New("functional", "go"))
//["FUNCTIONAL", "GO"]
Higher Order Functions - Filter
// As Golang do not have a builtin Filter implementation, it is possible use this one
// https://github.com/yanatan16/itertools/blob/master/itertools.go
pred := func (i interface{}) bool {
return i.(uint64) > 5
}
Filter(pred, Uint64(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
//[6, 7, 8, 9, 10]
Higher Order Functions - Reduce
// As Golang do not have a builtin Reduce implementation, it is possible use this one
// https://github.com/yanatan16/itertools/blob/master/itertools.go
acumullator := func (memo interface{}, el interface{}) interface{} {
return len(memo.(string)) + len(el.(string))
}
Reduce(New("functional", "go"), acumullator, string).(uint64)
// result 12
Higher Order Functions - Closure
func add_x(x int) func() int {
return func(y int) int { // anonymous function
return x + y
}
}
add_5 := add_x(5)
add_7 := add_x(7)
add_5(10) // result 15
add_7(10) // result 17
Currying and Partial Functions
Higher-order functions enable Currying, which the ability to take a function that accepts n
parameters and turns it into a composition of n functions each of them take 1 parameter. A direct
use of currying is the Partial Functions where if you have a function that accepts n parameters then
you can generate from it one of more functions with some parameter values already filled in.
func plus(x, y int) int {
return x + y
}
func partialPlus(x int) func(int) int {
return func(y int) int {
return plus(x, y)
}
}
func main() {
plus_one := partialPlus(1)
fmt.Println(plus_one(5)) //prints 6
}
Not Well Supported - Recursion
Not Well Supported - Recursion
Looping by calling a function from within itself. When you don’t have access to mutable
data, recursion is used to build up and chain data construction.
Not Well Supported - Recursion
Looping by calling a function from within itself. When you don’t have access to mutable
data, recursion is used to build up and chain data construction.
This is because looping is not a functional concept, as it requires variables to be passed
around to store the state of the loop at a given time.
Not Well Supported - Recursion
Looping by calling a function from within itself. When you don’t have access to mutable
data, recursion is used to build up and chain data construction.
This is because looping is not a functional concept, as it requires variables to be passed
around to store the state of the loop at a given time.
● Purely functional languages have no imperative for-loops, so they use recursion a lot.
Not Well Supported - Recursion
Looping by calling a function from within itself. When you don’t have access to mutable
data, recursion is used to build up and chain data construction.
This is because looping is not a functional concept, as it requires variables to be passed
around to store the state of the loop at a given time.
● Purely functional languages have no imperative for-loops, so they use recursion a lot.
● If every recursion created an stack, it would blow up very soon.
Not Well Supported - Recursion
Looping by calling a function from within itself. When you don’t have access to mutable
data, recursion is used to build up and chain data construction.
This is because looping is not a functional concept, as it requires variables to be passed
around to store the state of the loop at a given time.
● Purely functional languages have no imperative for-loops, so they use recursion a lot.
● If every recursion created an stack, it would blow up very soon.
● Tail-call optimization (TCO) avoids creating a new stack when the last call in a
recursion is the function itself.
Not Well Supported - Recursion
Looping by calling a function from within itself. When you don’t have access to mutable
data, recursion is used to build up and chain data construction.
This is because looping is not a functional concept, as it requires variables to be passed
around to store the state of the loop at a given time.
● Purely functional languages have no imperative for-loops, so they use recursion a lot.
● If every recursion created an stack, it would blow up very soon.
● Tail-call optimization (TCO) avoids creating a new stack when the last call in a
recursion is the function itself.
● TCO is not implemented in Golang.
Not Well Supported - Recursion
Looping by calling a function from within itself. When you don’t have access to mutable
data, recursion is used to build up and chain data construction.
This is because looping is not a functional concept, as it requires variables to be passed
around to store the state of the loop at a given time.
● Purely functional languages have no imperative for-loops, so they use recursion a lot.
● If every recursion created an stack, it would blow up very soon.
● Tail-call optimization (TCO) avoids creating a new stack when the last call in a
recursion is the function itself.
● TCO is not implemented in Golang.
● Unfortunately following recursion style in Golang has it’s own tax: Performance.
Solving Golang Lack of TCO(Tail Call Optimization)
// The functional solution have problems with big values
func fibonacciRecursive(n int) int {
if n <= 1 {
return n
}
return n * fibonacciRecursive(n - 1)
}
Solving Golang Lack of TCO(Tail Call Optimization)
// The iterative solution works perfectly with large values
func fibonacci(n int) int {
current, prev := 0, 1
for i := 0; i < n; i++ {
current, prev = current + prev, current
}
return current
}
Not Well Supported - Eager vs Lazy Evaluation
Not Well Supported - Eager vs Lazy Evaluation
● Eager evaluation: expressions are calculated at the moment that variables is
assined, function called...
Not Well Supported - Eager vs Lazy Evaluation
● Eager evaluation: expressions are calculated at the moment that variables is
assined, function called...
● Lazy evaluation: delays the evaluation of the expression until it is needed.
○ Memory efficient: no memory used to store complete structures.
○ CPU efficient: no need to calculate the complete result before returning.
○ Laziness is not a requisite for FP, but it is a strategy that fits nicely on
the paradigm(Haskell).
Not Well Supported - Eager vs Lazy Evaluation
● Eager evaluation: expressions are calculated at the moment that variables is
assined, function called...
● Lazy evaluation: delays the evaluation of the expression until it is needed.
○ Memory efficient: no memory used to store complete structures.
○ CPU efficient: no need to calculate the complete result before returning.
○ Laziness is not a requisite for FP, but it is a strategy that fits nicely on
the paradigm(Haskell).
Golang uses eager evaluation (but short-circuits && or ||).
Not Well Supported - Eager vs Lazy Evaluation
● Eager evaluation: expressions are calculated at the moment that variables is
assined, function called...
● Lazy evaluation: delays the evaluation of the expression until it is needed.
○ Memory efficient: no memory used to store complete structures.
○ CPU efficient: no need to calculate the complete result before returning.
○ Laziness is not a requisite for FP, but it is a strategy that fits nicely on
the paradigm(Haskell).
Golang uses eager evaluation (but short-circuits && or ||).
Golang channels and goroutines enable the creation of generators that could be a way
to have lazy evaluation.
Not Well Supported - Eager vs Lazy Evaluation
● Eager evaluation: expressions are calculated at the moment that variables is
assined, function called...
● Lazy evaluation: delays the evaluation of the expression until it is needed.
○ Memory efficient: no memory used to store complete structures.
○ CPU efficient: no need to calculate the complete result before returning.
○ Laziness is not a requisite for FP, but it is a strategy that fits nicely on
the paradigm(Haskell).
Golang uses eager evaluation (but short-circuits && or ||).
Golang channels and goroutines enable the creation of generators that could be a way
to have lazy evaluation.
Golang arrays are not lazy, use channels and goroutines to emulate a generator when
necessary.
Example of Golang generator using goroutine and channel
func fib(n int) chan int {
c := make(chan int) // create a channel
go func() { // keyword "go" starts a goroutine
x, y := 0, 1
for k := 0; k < n; k++ {
c <- x // send value x to the channel c
x, y = y, x + y // swap
}
close(c) // close(c) sets the status of the channel c to false
// indicates that the channel is now empty
}()
return c
}
Example of Golang generator using goroutine and channel
func main() {
fc := fib(5)
fmt.Println("The first 5 Fibonacci numbers:", <-fc, <-fc, <-fc, <-fc, <-fc)
// The first 5 Fibonacci numbers: 0 1 1 2 3
// trap the possible end of supply this way
fc2 := fib(5)
fmt.Println("The next 5 Fibonacci numbers:")
for k := 0; k < 6; k++ {
val, status := <-fc2
if status == false {
fmt.Println("channel empty")
break
}
fmt.Printf("%d ", val)
}
//The next 12 Fibonacci numbers:
//0 1 1 2 3 channel empty
}
A Practical Example
A Practical Example
Exercise: "What's the sum of the first 10 natural number whose square value is
divisible by 5?"
A Practical Example
Exercise: "What's the sum of the first 10 natural number whose square value is
divisible by 5?"
Imperative:
func main() {
n, numElements, s := 1, 0, 0
for numElements < 10 {
if n * n % 5 == 0 {
s += n
numElements++
}
n++
}
fmt.Println(s) //275
}
A Practical Example
Exercise: "What's the sum of the first 10 natural number whose square value is
divisible by 5?"
Imperative: Functional:
sum := func(memo interface{}, el interface{}) interface{} {
return memo.(float64) + el.(float64)
}
pred := func(i interface{}) bool {
return (i.(uint64) * i.(uint64)) % 5 == 0
}
createValues := func() []int {
values := make([]int, 100)
for num := 1; num <= 100; num++ {
values = append(values, num)
}
return values
}
Reduce(Filter(pred, createValues), sum, uint64).(uint64) //275
func main() {
n, numElements, s := 1, 0, 0
for numElements < 10 {
if n * n % 5 == 0 {
s += n
numElements++
}
n++
}
fmt.Println(s) //275
}
Conclusion
Conclusion
● As you can tell, Golang helps you write in functional style but it doesn’t force
you to it.
Conclusion
● As you can tell, Golang helps you write in functional style but it doesn’t force
you to it.
● Writing in functional style enhances your code and makes it more self documented.
Actually it will make it more thread-safe also.
Conclusion
● As you can tell, Golang helps you write in functional style but it doesn’t force
you to it.
● Writing in functional style enhances your code and makes it more self documented.
Actually it will make it more thread-safe also.
● The main support for FP in Golang comes from the use of closures, iterators and
generators.
Conclusion
● As you can tell, Golang helps you write in functional style but it doesn’t force
you to it.
● Writing in functional style enhances your code and makes it more self documented.
Actually it will make it more thread-safe also.
● The main support for FP in Golang comes from the use of closures, iterators and
generators.
● Golang still lack an important aspect of FP: Map, Filter, Reduce, Immutable and
Generic types, Pattern Matching and Tails Recursion.
Conclusion
● As you can tell, Golang helps you write in functional style but it doesn’t force
you to it.
● Writing in functional style enhances your code and makes it more self documented.
Actually it will make it more thread-safe also.
● The main support for FP in Golang comes from the use of closures, iterators and
generators.
● Golang still lack an important aspect of FP: Map, Filter, Reduce, Immutable and
Generic types, Pattern Matching and Tails Recursion.
● There should be more work on tail recursion optimization, to encourage developers
to use recursion.
The last advice
Learn at least one functional language, it will open your mind to a new paradigm
becoming you a better programmer.
The last advice
Learn at least one functional language, it will open your mind to a new paradigm
becoming you a better programmer.
Some Functional Languages:
● Haskell
● ML (Standard ML, Objective Caml, ...)
● Scheme
● Erlang
● Scala
● Closure
● F#
OBRIGADO!
Email: geisonfgf@gmail.com
Skype: geisonfgf
Facebook: http://www.facebook.com/geisonfgf
Twitter: http://www.twitter.com/geisonfgf
References
● http://en.wikipedia.org/wiki/Functional_programming
● http://www.cse.chalmers.se/~rjmh/Papers/whyfp.pdf
● http://tour.golang.org
● http://www.golangpatterns.info/
● https://github.com/yanatan16/itertools
● http://clojure.org/
● http://www.defmacro.org/ramblings/fp.html

More Related Content

What's hot

Ruby Functional Programming
Ruby Functional ProgrammingRuby Functional Programming
Ruby Functional ProgrammingGeison Goes
 
Functional programming and ruby in functional style
Functional programming and ruby in functional styleFunctional programming and ruby in functional style
Functional programming and ruby in functional styleNiranjan Sarade
 
Python functional programming
Python functional programmingPython functional programming
Python functional programmingGeison Goes
 
Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)Omar Abdelhafith
 
Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonAnoop Thomas Mathew
 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scalaStratio
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programmingKonrad Szydlo
 
Functional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smartFunctional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smartChen Fisher
 
User Defined Functions in MATLAB part 2
User Defined Functions in MATLAB part 2User Defined Functions in MATLAB part 2
User Defined Functions in MATLAB part 2Shameer Ahmed Koya
 
Anonymous and Inline Functions in MATLAB
Anonymous and Inline Functions in MATLABAnonymous and Inline Functions in MATLAB
Anonymous and Inline Functions in MATLABShameer Ahmed Koya
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parametersKnoldus Inc.
 
Teach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with ScalaTeach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with ScalaDamian Jureczko
 
It's All About Morphisms
It's All About MorphismsIt's All About Morphisms
It's All About MorphismsUberto Barbini
 
Aaa ped-2- Python: Basics
Aaa ped-2- Python: BasicsAaa ped-2- Python: Basics
Aaa ped-2- Python: BasicsAminaRepo
 
Scala: functional programming for the imperative mind
Scala: functional programming for the imperative mindScala: functional programming for the imperative mind
Scala: functional programming for the imperative mindSander Mak (@Sander_Mak)
 
User defined Functions in MATLAB Part 1
User defined Functions in MATLAB Part 1User defined Functions in MATLAB Part 1
User defined Functions in MATLAB Part 1Shameer Ahmed Koya
 
Data weave 2.0 advanced (recursion, pattern matching)
Data weave 2.0   advanced (recursion, pattern matching)Data weave 2.0   advanced (recursion, pattern matching)
Data weave 2.0 advanced (recursion, pattern matching)ManjuKumara GH
 

What's hot (20)

Ruby Functional Programming
Ruby Functional ProgrammingRuby Functional Programming
Ruby Functional Programming
 
Functional programming and ruby in functional style
Functional programming and ruby in functional styleFunctional programming and ruby in functional style
Functional programming and ruby in functional style
 
Python functional programming
Python functional programmingPython functional programming
Python functional programming
 
Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)
 
Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in Python
 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scala
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programming
 
Functional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smartFunctional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smart
 
User Defined Functions in MATLAB part 2
User Defined Functions in MATLAB part 2User Defined Functions in MATLAB part 2
User Defined Functions in MATLAB part 2
 
JavaScript operators
JavaScript operatorsJavaScript operators
JavaScript operators
 
Anonymous and Inline Functions in MATLAB
Anonymous and Inline Functions in MATLABAnonymous and Inline Functions in MATLAB
Anonymous and Inline Functions in MATLAB
 
Python ppt
Python pptPython ppt
Python ppt
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
 
Teach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with ScalaTeach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with Scala
 
It's All About Morphisms
It's All About MorphismsIt's All About Morphisms
It's All About Morphisms
 
Some basic FP concepts
Some basic FP conceptsSome basic FP concepts
Some basic FP concepts
 
Aaa ped-2- Python: Basics
Aaa ped-2- Python: BasicsAaa ped-2- Python: Basics
Aaa ped-2- Python: Basics
 
Scala: functional programming for the imperative mind
Scala: functional programming for the imperative mindScala: functional programming for the imperative mind
Scala: functional programming for the imperative mind
 
User defined Functions in MATLAB Part 1
User defined Functions in MATLAB Part 1User defined Functions in MATLAB Part 1
User defined Functions in MATLAB Part 1
 
Data weave 2.0 advanced (recursion, pattern matching)
Data weave 2.0   advanced (recursion, pattern matching)Data weave 2.0   advanced (recursion, pattern matching)
Data weave 2.0 advanced (recursion, pattern matching)
 

Similar to Functional Go

Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programmingDhaval Dalal
 
pure-functional-programming.pdf
pure-functional-programming.pdfpure-functional-programming.pdf
pure-functional-programming.pdfPuneetChaturvedi23
 
Jumping-with-java8
Jumping-with-java8Jumping-with-java8
Jumping-with-java8Dhaval Dalal
 
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Ovidiu Farauanu
 
DataWeave 2.0 Language Fundamentals
DataWeave 2.0 Language FundamentalsDataWeave 2.0 Language Fundamentals
DataWeave 2.0 Language FundamentalsJoshua Erney
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programmingNico Ludwig
 
Definitions of Functional Programming
Definitions of Functional ProgrammingDefinitions of Functional Programming
Definitions of Functional ProgrammingPhilip Schwarz
 
Vendredi Tech_ la programmation fonctionnelle.pptx
Vendredi Tech_ la programmation fonctionnelle.pptxVendredi Tech_ la programmation fonctionnelle.pptx
Vendredi Tech_ la programmation fonctionnelle.pptxGuillaume Saint Etienne
 
Intro to Functional Programming @ Scala Montreal
Intro to Functional Programming @ Scala MontrealIntro to Functional Programming @ Scala Montreal
Intro to Functional Programming @ Scala Montrealfelixtrepanier
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
 
Functional programming in clojure
Functional programming in clojureFunctional programming in clojure
Functional programming in clojureJuan-Manuel Gimeno
 
Functional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative ProgrammersFunctional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative ProgrammersChris
 
How To Use IO Monads in Scala?
 How To Use IO Monads in Scala? How To Use IO Monads in Scala?
How To Use IO Monads in Scala?Knoldus Inc.
 
Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)Calvin Cheng
 
The Functional Programming Toolkit (NDC Oslo 2019)
The Functional Programming Toolkit (NDC Oslo 2019)The Functional Programming Toolkit (NDC Oslo 2019)
The Functional Programming Toolkit (NDC Oslo 2019)Scott Wlaschin
 
Functional programing jargon
Functional programing jargonFunctional programing jargon
Functional programing jargonRemo Jansen
 

Similar to Functional Go (20)

Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programming
 
pure-functional-programming.pdf
pure-functional-programming.pdfpure-functional-programming.pdf
pure-functional-programming.pdf
 
Jumping-with-java8
Jumping-with-java8Jumping-with-java8
Jumping-with-java8
 
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
 
DataWeave 2.0 Language Fundamentals
DataWeave 2.0 Language FundamentalsDataWeave 2.0 Language Fundamentals
DataWeave 2.0 Language Fundamentals
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
 
Definitions of Functional Programming
Definitions of Functional ProgrammingDefinitions of Functional Programming
Definitions of Functional Programming
 
Vendredi Tech_ la programmation fonctionnelle.pptx
Vendredi Tech_ la programmation fonctionnelle.pptxVendredi Tech_ la programmation fonctionnelle.pptx
Vendredi Tech_ la programmation fonctionnelle.pptx
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Intro to Functional Programming @ Scala Montreal
Intro to Functional Programming @ Scala MontrealIntro to Functional Programming @ Scala Montreal
Intro to Functional Programming @ Scala Montreal
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
Basics of cpp
Basics of cppBasics of cpp
Basics of cpp
 
Functional Programming in Java
Functional Programming in JavaFunctional Programming in Java
Functional Programming in Java
 
Functional programming in clojure
Functional programming in clojureFunctional programming in clojure
Functional programming in clojure
 
Function
FunctionFunction
Function
 
Functional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative ProgrammersFunctional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative Programmers
 
How To Use IO Monads in Scala?
 How To Use IO Monads in Scala? How To Use IO Monads in Scala?
How To Use IO Monads in Scala?
 
Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)
 
The Functional Programming Toolkit (NDC Oslo 2019)
The Functional Programming Toolkit (NDC Oslo 2019)The Functional Programming Toolkit (NDC Oslo 2019)
The Functional Programming Toolkit (NDC Oslo 2019)
 
Functional programing jargon
Functional programing jargonFunctional programing jargon
Functional programing jargon
 

More from Geison Goes

Kotlin multiplataforma
Kotlin multiplataformaKotlin multiplataforma
Kotlin multiplataformaGeison Goes
 
Why companies like Google, Alibaba and UOL choose Flutter
Why companies like Google, Alibaba and UOL choose FlutterWhy companies like Google, Alibaba and UOL choose Flutter
Why companies like Google, Alibaba and UOL choose FlutterGeison Goes
 
Restful design principles
Restful design principlesRestful design principles
Restful design principlesGeison Goes
 
Cucumber - use it to describe user stories and acceptance criterias
Cucumber - use it to describe user stories and acceptance criteriasCucumber - use it to describe user stories and acceptance criterias
Cucumber - use it to describe user stories and acceptance criteriasGeison Goes
 
Gil - the responsible to unable paralellism
Gil - the responsible to unable paralellismGil - the responsible to unable paralellism
Gil - the responsible to unable paralellismGeison Goes
 
An introduction to the ruby ecosystem
An introduction to the ruby ecosystemAn introduction to the ruby ecosystem
An introduction to the ruby ecosystemGeison Goes
 

More from Geison Goes (7)

Kotlin multiplataforma
Kotlin multiplataformaKotlin multiplataforma
Kotlin multiplataforma
 
Why companies like Google, Alibaba and UOL choose Flutter
Why companies like Google, Alibaba and UOL choose FlutterWhy companies like Google, Alibaba and UOL choose Flutter
Why companies like Google, Alibaba and UOL choose Flutter
 
Restful design principles
Restful design principlesRestful design principles
Restful design principles
 
Cucumber - use it to describe user stories and acceptance criterias
Cucumber - use it to describe user stories and acceptance criteriasCucumber - use it to describe user stories and acceptance criterias
Cucumber - use it to describe user stories and acceptance criterias
 
Gil - the responsible to unable paralellism
Gil - the responsible to unable paralellismGil - the responsible to unable paralellism
Gil - the responsible to unable paralellism
 
An introduction to the ruby ecosystem
An introduction to the ruby ecosystemAn introduction to the ruby ecosystem
An introduction to the ruby ecosystem
 
Python Flavors
Python FlavorsPython Flavors
Python Flavors
 

Recently uploaded

Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 

Recently uploaded (20)

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 

Functional Go

  • 2. Functional Programming by Wikipidia: “Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data". In other words, functional programming promotes code with no side effects, no change of value in variables. It oposes to imperative programming, which emphasizes change of state”.
  • 4. What this means? ● No mutable data (no side effect).
  • 5. What this means? ● No mutable data (no side effect). ● No state (no implicit, hidden state). Once assigned (value binding), a variable (a symbol) does not change its value
  • 6. What this means? ● No mutable data (no side effect). ● No state (no implicit, hidden state). Once assigned (value binding), a variable (a symbol) does not change its value. All state is bad? No, hidden, implicit state is bad.
  • 7. What this means? ● No mutable data (no side effect). ● No state (no implicit, hidden state). Once assigned (value binding), a variable (a symbol) does not change its value. All state is bad? No, hidden, implicit state is bad. Functional programming do not eliminate state, it just make it visible and explicit (at least when programmers want it to be).
  • 8. What this means? ● No mutable data (no side effect). ● No state (no implicit, hidden state). Once assigned (value binding), a variable (a symbol) does not change its value. All state is bad? No, hidden, implicit state is bad. Functional programming do not eliminate state, it just make it visible and explicit (at least when programmers want it to be). ● Functions are pure functions in the mathematical sense: their output depend only in their inputs, there is not “environment”.
  • 9. What this means? ● No mutable data (no side effect). ● No state (no implicit, hidden state). Once assigned (value binding), a variable (a symbol) does not change its value. All state is bad? No, hidden, implicit state is bad. Functional programming do not eliminate state, it just make it visible and explicit (at least when programmers want it to be). ● Functions are pure functions in the mathematical sense: their output depend only in their inputs, there is not “environment”. ● Same result returned by functions called with the same inputs.
  • 10. What are the advantages?
  • 11. What are the advantages? ● Cleaner code: "variables" are not modified once defined, so we don't have to follow the change of state to comprehend what a function, a, method, a class, a whole project works.
  • 12. What are the advantages? ● Cleaner code: "variables" are not modified once defined, so we don't have to follow the change of state to comprehend what a function, a, method, a class, a whole project works. ● Referential transparency: Expressions can be replaced by its values. If we call a function with the same parameters, we know for sure the output will be the same (there is no state anywhere that would change it).
  • 13. What are the advantages? ● Cleaner code: "variables" are not modified once defined, so we don't have to follow the change of state to comprehend what a function, a, method, a class, a whole project works. ● Referential transparency: Expressions can be replaced by its values. If we call a function with the same parameters, we know for sure the output will be the same (there is no state anywhere that would change it). There is a reason for which Einstein defined insanity as "doing the same thing over and over again and expecting different results".
  • 14. Advantages enabled by referential transparency
  • 15. Advantages enabled by referential transparency ● Memoization ○ Cache results for previous function calls.
  • 16. Advantages enabled by referential transparency ● Memoization ○ Cache results for previous function calls. ● Idempotence ○ Same results regardless how many times you call a function.
  • 17. Advantages enabled by referential transparency ● Memoization ○ Cache results for previous function calls. ● Idempotence ○ Same results regardless how many times you call a function. ● Modularization ○ We have no state that pervades the whole code, so we build our project with small, black boxes that we tie together, so it promotes bottom-up programming.
  • 18. Advantages enabled by referential transparency ● Memoization ○ Cache results for previous function calls. ● Idempotence ○ Same results regardless how many times you call a function. ● Modularization ○ We have no state that pervades the whole code, so we build our project with small, black boxes that we tie together, so it promotes bottom-up programming. ● Ease of debugging ○ Functions are isolated, they only depend on their input and their output, so they are very easy to debug.
  • 19. Advantages enabled by referential transparency ● Parallelization ○ Functions calls are independent. ○ We can parallelize in different process/CPUs/computers/…
  • 20. Advantages enabled by referential transparency ● Parallelization ○ Functions calls are independent. ○ We can parallelize in different process/CPUs/computers/… result = func1(a, b) + func2(a, c)
  • 21. Advantages enabled by referential transparency ● Parallelization ○ Functions calls are independent. ○ We can parallelize in different process/CPUs/computers/… We can execute func1 and func2 in parallel because an won’t be modified. result = func1(a, b) + func2(a, c)
  • 22. Advantages enabled by referential transparency ● Concurrence ○ With no shared data, concurrence gets a lot simpler: ■ No semaphores. ■ No monitors. ■ No locks. ■ No race-conditions. ■ No dead-locks.
  • 23. Ok so let's play a little with functional programming?
  • 24. Don’t Update, Create - String name := "Geison" name = name + " Flores"
  • 25. Don’t Update, Create - String name := "Geison" name = name + " Flores" const firstname = "Geison" const lastname = "Flores" const name = firstname + " " + lastname
  • 26. Don’t Update, Create - Arrays years := [4]int{2001, 2002} years[2] = 2003 years[3] = 2004 years // [2001, 2002, 2003, 2004]
  • 27. Don’t Update, Create - Arrays years := [4]int{2001, 2002} years[2] = 2003 years[3] = 2004 years // [2001, 2002, 2003, 2004] years := []{2001, 2003} allYears := append(years, []int{2003, 2004}...)
  • 28. Don’t Update, Create - Maps ages := map[string]int{"John": 30} ages["Mary"] = 28 ages // {"John": 30, "Mary": 28}
  • 29. Don’t Update, Create - Maps ages := map[string]int{"John": 30} ages["Mary"] = 28 ages // {"John": 30, "Mary": 28} ages1 := map[string]int{"John": 30} ages2 := map[string]int{"Mary": 28} func mergeMaps(mapA, mapB map[string]int) map[string]int { allAges := make(map[string]int, len(mapA) + len(mapB)) for k, v := range mapA { allAges[k] = v } for k, v := range mapB { allAges[k] = v } return allAges } allAges := mergeMaps(ages1, ages2)
  • 30. Higher Order Functions Functions and methods are first-class objects in Golang, so if you want to pass a function to another function, you can just treat it as any other object. func caller(f func(string) string) { result := f("David") fmt.Println(result) } f := func(name string) string { return "Hello " + name } caller(f)
  • 31. Higher Order Functions - Map // As Golang do not have a builtin Map implementation, it is possible use this one // https://github.com/yanatan16/itertools/blob/master/itertools.go mapper := func (i interface{}) interface{} { return strings.ToUpper(i.(string)) } Map(mapper, New("functional", "go")) //["FUNCTIONAL", "GO"]
  • 32. Higher Order Functions - Filter // As Golang do not have a builtin Filter implementation, it is possible use this one // https://github.com/yanatan16/itertools/blob/master/itertools.go pred := func (i interface{}) bool { return i.(uint64) > 5 } Filter(pred, Uint64(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) //[6, 7, 8, 9, 10]
  • 33. Higher Order Functions - Reduce // As Golang do not have a builtin Reduce implementation, it is possible use this one // https://github.com/yanatan16/itertools/blob/master/itertools.go acumullator := func (memo interface{}, el interface{}) interface{} { return len(memo.(string)) + len(el.(string)) } Reduce(New("functional", "go"), acumullator, string).(uint64) // result 12
  • 34. Higher Order Functions - Closure func add_x(x int) func() int { return func(y int) int { // anonymous function return x + y } } add_5 := add_x(5) add_7 := add_x(7) add_5(10) // result 15 add_7(10) // result 17
  • 35. Currying and Partial Functions Higher-order functions enable Currying, which the ability to take a function that accepts n parameters and turns it into a composition of n functions each of them take 1 parameter. A direct use of currying is the Partial Functions where if you have a function that accepts n parameters then you can generate from it one of more functions with some parameter values already filled in. func plus(x, y int) int { return x + y } func partialPlus(x int) func(int) int { return func(y int) int { return plus(x, y) } } func main() { plus_one := partialPlus(1) fmt.Println(plus_one(5)) //prints 6 }
  • 36. Not Well Supported - Recursion
  • 37. Not Well Supported - Recursion Looping by calling a function from within itself. When you don’t have access to mutable data, recursion is used to build up and chain data construction.
  • 38. Not Well Supported - Recursion Looping by calling a function from within itself. When you don’t have access to mutable data, recursion is used to build up and chain data construction. This is because looping is not a functional concept, as it requires variables to be passed around to store the state of the loop at a given time.
  • 39. Not Well Supported - Recursion Looping by calling a function from within itself. When you don’t have access to mutable data, recursion is used to build up and chain data construction. This is because looping is not a functional concept, as it requires variables to be passed around to store the state of the loop at a given time. ● Purely functional languages have no imperative for-loops, so they use recursion a lot.
  • 40. Not Well Supported - Recursion Looping by calling a function from within itself. When you don’t have access to mutable data, recursion is used to build up and chain data construction. This is because looping is not a functional concept, as it requires variables to be passed around to store the state of the loop at a given time. ● Purely functional languages have no imperative for-loops, so they use recursion a lot. ● If every recursion created an stack, it would blow up very soon.
  • 41. Not Well Supported - Recursion Looping by calling a function from within itself. When you don’t have access to mutable data, recursion is used to build up and chain data construction. This is because looping is not a functional concept, as it requires variables to be passed around to store the state of the loop at a given time. ● Purely functional languages have no imperative for-loops, so they use recursion a lot. ● If every recursion created an stack, it would blow up very soon. ● Tail-call optimization (TCO) avoids creating a new stack when the last call in a recursion is the function itself.
  • 42. Not Well Supported - Recursion Looping by calling a function from within itself. When you don’t have access to mutable data, recursion is used to build up and chain data construction. This is because looping is not a functional concept, as it requires variables to be passed around to store the state of the loop at a given time. ● Purely functional languages have no imperative for-loops, so they use recursion a lot. ● If every recursion created an stack, it would blow up very soon. ● Tail-call optimization (TCO) avoids creating a new stack when the last call in a recursion is the function itself. ● TCO is not implemented in Golang.
  • 43. Not Well Supported - Recursion Looping by calling a function from within itself. When you don’t have access to mutable data, recursion is used to build up and chain data construction. This is because looping is not a functional concept, as it requires variables to be passed around to store the state of the loop at a given time. ● Purely functional languages have no imperative for-loops, so they use recursion a lot. ● If every recursion created an stack, it would blow up very soon. ● Tail-call optimization (TCO) avoids creating a new stack when the last call in a recursion is the function itself. ● TCO is not implemented in Golang. ● Unfortunately following recursion style in Golang has it’s own tax: Performance.
  • 44. Solving Golang Lack of TCO(Tail Call Optimization) // The functional solution have problems with big values func fibonacciRecursive(n int) int { if n <= 1 { return n } return n * fibonacciRecursive(n - 1) }
  • 45. Solving Golang Lack of TCO(Tail Call Optimization) // The iterative solution works perfectly with large values func fibonacci(n int) int { current, prev := 0, 1 for i := 0; i < n; i++ { current, prev = current + prev, current } return current }
  • 46. Not Well Supported - Eager vs Lazy Evaluation
  • 47. Not Well Supported - Eager vs Lazy Evaluation ● Eager evaluation: expressions are calculated at the moment that variables is assined, function called...
  • 48. Not Well Supported - Eager vs Lazy Evaluation ● Eager evaluation: expressions are calculated at the moment that variables is assined, function called... ● Lazy evaluation: delays the evaluation of the expression until it is needed. ○ Memory efficient: no memory used to store complete structures. ○ CPU efficient: no need to calculate the complete result before returning. ○ Laziness is not a requisite for FP, but it is a strategy that fits nicely on the paradigm(Haskell).
  • 49. Not Well Supported - Eager vs Lazy Evaluation ● Eager evaluation: expressions are calculated at the moment that variables is assined, function called... ● Lazy evaluation: delays the evaluation of the expression until it is needed. ○ Memory efficient: no memory used to store complete structures. ○ CPU efficient: no need to calculate the complete result before returning. ○ Laziness is not a requisite for FP, but it is a strategy that fits nicely on the paradigm(Haskell). Golang uses eager evaluation (but short-circuits && or ||).
  • 50. Not Well Supported - Eager vs Lazy Evaluation ● Eager evaluation: expressions are calculated at the moment that variables is assined, function called... ● Lazy evaluation: delays the evaluation of the expression until it is needed. ○ Memory efficient: no memory used to store complete structures. ○ CPU efficient: no need to calculate the complete result before returning. ○ Laziness is not a requisite for FP, but it is a strategy that fits nicely on the paradigm(Haskell). Golang uses eager evaluation (but short-circuits && or ||). Golang channels and goroutines enable the creation of generators that could be a way to have lazy evaluation.
  • 51. Not Well Supported - Eager vs Lazy Evaluation ● Eager evaluation: expressions are calculated at the moment that variables is assined, function called... ● Lazy evaluation: delays the evaluation of the expression until it is needed. ○ Memory efficient: no memory used to store complete structures. ○ CPU efficient: no need to calculate the complete result before returning. ○ Laziness is not a requisite for FP, but it is a strategy that fits nicely on the paradigm(Haskell). Golang uses eager evaluation (but short-circuits && or ||). Golang channels and goroutines enable the creation of generators that could be a way to have lazy evaluation. Golang arrays are not lazy, use channels and goroutines to emulate a generator when necessary.
  • 52. Example of Golang generator using goroutine and channel func fib(n int) chan int { c := make(chan int) // create a channel go func() { // keyword "go" starts a goroutine x, y := 0, 1 for k := 0; k < n; k++ { c <- x // send value x to the channel c x, y = y, x + y // swap } close(c) // close(c) sets the status of the channel c to false // indicates that the channel is now empty }() return c }
  • 53. Example of Golang generator using goroutine and channel func main() { fc := fib(5) fmt.Println("The first 5 Fibonacci numbers:", <-fc, <-fc, <-fc, <-fc, <-fc) // The first 5 Fibonacci numbers: 0 1 1 2 3 // trap the possible end of supply this way fc2 := fib(5) fmt.Println("The next 5 Fibonacci numbers:") for k := 0; k < 6; k++ { val, status := <-fc2 if status == false { fmt.Println("channel empty") break } fmt.Printf("%d ", val) } //The next 12 Fibonacci numbers: //0 1 1 2 3 channel empty }
  • 55. A Practical Example Exercise: "What's the sum of the first 10 natural number whose square value is divisible by 5?"
  • 56. A Practical Example Exercise: "What's the sum of the first 10 natural number whose square value is divisible by 5?" Imperative: func main() { n, numElements, s := 1, 0, 0 for numElements < 10 { if n * n % 5 == 0 { s += n numElements++ } n++ } fmt.Println(s) //275 }
  • 57. A Practical Example Exercise: "What's the sum of the first 10 natural number whose square value is divisible by 5?" Imperative: Functional: sum := func(memo interface{}, el interface{}) interface{} { return memo.(float64) + el.(float64) } pred := func(i interface{}) bool { return (i.(uint64) * i.(uint64)) % 5 == 0 } createValues := func() []int { values := make([]int, 100) for num := 1; num <= 100; num++ { values = append(values, num) } return values } Reduce(Filter(pred, createValues), sum, uint64).(uint64) //275 func main() { n, numElements, s := 1, 0, 0 for numElements < 10 { if n * n % 5 == 0 { s += n numElements++ } n++ } fmt.Println(s) //275 }
  • 59. Conclusion ● As you can tell, Golang helps you write in functional style but it doesn’t force you to it.
  • 60. Conclusion ● As you can tell, Golang helps you write in functional style but it doesn’t force you to it. ● Writing in functional style enhances your code and makes it more self documented. Actually it will make it more thread-safe also.
  • 61. Conclusion ● As you can tell, Golang helps you write in functional style but it doesn’t force you to it. ● Writing in functional style enhances your code and makes it more self documented. Actually it will make it more thread-safe also. ● The main support for FP in Golang comes from the use of closures, iterators and generators.
  • 62. Conclusion ● As you can tell, Golang helps you write in functional style but it doesn’t force you to it. ● Writing in functional style enhances your code and makes it more self documented. Actually it will make it more thread-safe also. ● The main support for FP in Golang comes from the use of closures, iterators and generators. ● Golang still lack an important aspect of FP: Map, Filter, Reduce, Immutable and Generic types, Pattern Matching and Tails Recursion.
  • 63. Conclusion ● As you can tell, Golang helps you write in functional style but it doesn’t force you to it. ● Writing in functional style enhances your code and makes it more self documented. Actually it will make it more thread-safe also. ● The main support for FP in Golang comes from the use of closures, iterators and generators. ● Golang still lack an important aspect of FP: Map, Filter, Reduce, Immutable and Generic types, Pattern Matching and Tails Recursion. ● There should be more work on tail recursion optimization, to encourage developers to use recursion.
  • 64. The last advice Learn at least one functional language, it will open your mind to a new paradigm becoming you a better programmer.
  • 65. The last advice Learn at least one functional language, it will open your mind to a new paradigm becoming you a better programmer. Some Functional Languages: ● Haskell ● ML (Standard ML, Objective Caml, ...) ● Scheme ● Erlang ● Scala ● Closure ● F#
  • 66. OBRIGADO! Email: geisonfgf@gmail.com Skype: geisonfgf Facebook: http://www.facebook.com/geisonfgf Twitter: http://www.twitter.com/geisonfgf
  • 67. References ● http://en.wikipedia.org/wiki/Functional_programming ● http://www.cse.chalmers.se/~rjmh/Papers/whyfp.pdf ● http://tour.golang.org ● http://www.golangpatterns.info/ ● https://github.com/yanatan16/itertools ● http://clojure.org/ ● http://www.defmacro.org/ramblings/fp.html