SlideShare a Scribd company logo
1 of 27
Download to read offline
+ =f(x)
Functional Go
???
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 enfatizes
change of state”.
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.
Functional Go
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".
Functional Go
Advantages enabled by referential transparence
● 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.
Functional Go
Advantages enabled by referential transparence
● Parallelization
○ Functions calls are independent.
○ We can parallelize in different process/CPUs/computers/…
We can execute func1 and func2 in paralell because a won’t be modified.
result = func1(a, b) + func2(a, c)
Functional Go
Advantages enabled by referential transparence
● Concurrence
a. With no shared data, concurrence gets a lot simpler:
i. No semaphores.
ii. No monitors.
iii. No locks.
iv. No race-conditions.
v. No dead-locks.
Functional Go
Golang is a multi paradigm programming language. As a Golang
programmer why uses functional programming?
Golang is not a functional language but have a lot of features that enables us to
applies functional principles in the development, turning our code more elegant,
concise, maintanable, easier to understand and test.
Functional Go
Don’t Update, Create - String
name := "Geison"
name := name + " Flores"
const firstname = "Geison"
const lasname = "Flores"
const name = firstname + " " + lastname
Functional Go
Don’t Update, Create - Arrays
years := [4]int{2001, 2002}
years[2] = 2003
years[3] = 2004
years // [2001, 2002, 2003, 2004]
years := [2]{2001, 2001}
allYears := append(years, 2003, [2]int{2004, 2005}
Functional Go
Don’t Update, Create - Maps
ages := map[string]int{"John": 30}
ages["Mary"] = 28
ages // {'John': 30, 'Mary': 28}
Functional Go
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[K]V, len(ages1) + len(ages2))
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(s name) string {
return "Hello " + name
}
caller(f)
Functional Go
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("milu", "rantanplan"))
//["MILU", "RANTANPLAN"]
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]
Functional Go
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("milu", "rantanplan"), acumullator, string).(uint64)
// result 14
Functional Go
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
Functional Go
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.
Functional Go
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
}
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.
Functional Go
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.
● Unfortunarely following recursion style in Golang has it’s own tax: Performance.
Functional Go
Solving Golang Lack of TCO(Tail Call Optimization)
// The functional solution have problens with big values
func fibonacciRecursive(n int) int {
if n <= 1 {
return n
}
return n * fibonacciRecursive(n - 1)
}
Functional Go
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
}
Functional Go
FP in OOP?
It is possible do FP in OOP? Yes it is!
● OOP is orthogonal to FP.
● Well, at least in theory, because:
○ Typical OOP tends to emphasize change of state in objects.
○ Typical OOP mixes the concepts of identity and state.
○ Mixture of data and code raises both conceptual and practical problems.
● OOP functional languages: Scala, F#, ...
Functional Go
A Pratical Example
Exercise: "What's the sum of the first 10 natural number whose square value is
divisible by 5?"
Imperative: Functional:
func main() {
n, numElements, s := 1, 0, 0
for numElements < 10 {
if n * n % 5 == 0 {
s += n
numElements++
}
n++
}
fmt.Println(s) //275
}
Functional Go
sum := func (memo interface{}, el interface{}) interface{} {
return memo.(float64) + el.(float64)
}
pred := func (i interface{}) bool {
return (i.(uint64) * i.(uint64)) % 5 == 0
}
values := make([]int, 100)
for num := 1; num <= 100; num++ {
values = append(values, num)
}
Reduce(Filter(pred, values), sum, uint64).(uint64)
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#
Functional Go
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.
● Any other thoughts?
Functional Go
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
Functional Go
Contact me
● Email:
○ geisonfgf@gmail.com
● Skype
○ geisonfgf
● Facebook
○ http://www.facebook.com/geisonfgf
● Twitter
○ http://www.twitter.com/geisonfgf
Functional Go

More Related Content

What's hot

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
 
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
 
Intro to functional programming
Intro to functional programmingIntro to functional programming
Intro to functional programmingAssaf Gannon
 
Introduction To Functional Programming
Introduction To Functional ProgrammingIntroduction To Functional Programming
Introduction To Functional Programmingnewmedio
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioLuis Atencio
 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programmingDhaval Dalal
 
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)
 
Intro to functional programming
Intro to functional programmingIntro to functional programming
Intro to functional programmingAssaf Gannon
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programmingNico Ludwig
 
Dev Concepts: Functional Programming
Dev Concepts: Functional ProgrammingDev Concepts: Functional Programming
Dev Concepts: Functional ProgrammingSvetlin Nakov
 
Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScriptJoseph Smith
 
An Introduction to Functional Programming with Javascript
An Introduction to Functional Programming with JavascriptAn Introduction to Functional Programming with Javascript
An Introduction to Functional Programming with JavascriptDoug Sparling
 
Functional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 DevelopersFunctional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 DevelopersJayaram Sankaranarayanan
 
Functional Programming Fundamentals
Functional Programming FundamentalsFunctional Programming Fundamentals
Functional Programming FundamentalsShahriar Hyder
 
Debugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template MetaprogramsDebugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template MetaprogramsPlatonov Sergey
 
Frege Tutorial at JavaOne 2015
Frege Tutorial at JavaOne 2015Frege Tutorial at JavaOne 2015
Frege Tutorial at JavaOne 2015Dierk König
 

What's hot (20)

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
 
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
 
Intro to functional programming
Intro to functional programmingIntro to functional programming
Intro to functional programming
 
Introduction To Functional Programming
Introduction To Functional ProgrammingIntroduction To Functional Programming
Introduction To Functional Programming
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programming
 
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
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Intro to functional programming
Intro to functional programmingIntro to functional programming
Intro to functional programming
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
 
Dev Concepts: Functional Programming
Dev Concepts: Functional ProgrammingDev Concepts: Functional Programming
Dev Concepts: Functional Programming
 
Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScript
 
An Introduction to Functional Programming with Javascript
An Introduction to Functional Programming with JavascriptAn Introduction to Functional Programming with Javascript
An Introduction to Functional Programming with Javascript
 
Client sidescripting javascript
Client sidescripting javascriptClient sidescripting javascript
Client sidescripting javascript
 
Functional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 DevelopersFunctional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 Developers
 
Functional Programming Fundamentals
Functional Programming FundamentalsFunctional Programming Fundamentals
Functional Programming Fundamentals
 
Some basic FP concepts
Some basic FP conceptsSome basic FP concepts
Some basic FP concepts
 
Debugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template MetaprogramsDebugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template Metaprograms
 
Frege Tutorial at JavaOne 2015
Frege Tutorial at JavaOne 2015Frege Tutorial at JavaOne 2015
Frege Tutorial at JavaOne 2015
 

Viewers also liked

A microservice architecture based on golang
A microservice architecture based on golangA microservice architecture based on golang
A microservice architecture based on golangGianfranco Reppucci
 
Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?Jérôme Petazzoni
 
Write microservice in golang
Write microservice in golangWrite microservice in golang
Write microservice in golangBo-Yi Wu
 
Golang server design pattern
Golang server design patternGolang server design pattern
Golang server design pattern理 傅
 
Develop Android app using Golang
Develop Android app using GolangDevelop Android app using Golang
Develop Android app using GolangSeongJae Park
 
マイクロサービスバックエンドAPIのためのRESTとgRPC
マイクロサービスバックエンドAPIのためのRESTとgRPCマイクロサービスバックエンドAPIのためのRESTとgRPC
マイクロサービスバックエンドAPIのためのRESTとgRPCdisc99_
 
ドメインロジックに集中せよ 〜ドメイン駆動設計 powered by Spring
ドメインロジックに集中せよ 〜ドメイン駆動設計 powered by Springドメインロジックに集中せよ 〜ドメイン駆動設計 powered by Spring
ドメインロジックに集中せよ 〜ドメイン駆動設計 powered by Spring増田 亨
 
Goをカンストさせる話
Goをカンストさせる話Goをカンストさせる話
Goをカンストさせる話Moriyoshi Koizumi
 
Architecting for the Cloud using NetflixOSS - Codemash Workshop
Architecting for the Cloud using NetflixOSS - Codemash WorkshopArchitecting for the Cloud using NetflixOSS - Codemash Workshop
Architecting for the Cloud using NetflixOSS - Codemash WorkshopSudhir Tonse
 
Memory Interoperability in Analytics and Machine Learning
Memory Interoperability in Analytics and Machine LearningMemory Interoperability in Analytics and Machine Learning
Memory Interoperability in Analytics and Machine LearningWes McKinney
 
13 practical tips for writing secure golang applications
13 practical tips for writing secure golang applications13 practical tips for writing secure golang applications
13 practical tips for writing secure golang applicationsKarthik Gaekwad
 
並行実行制御の最適化手法
並行実行制御の最適化手法並行実行制御の最適化手法
並行実行制御の最適化手法Sho Nakazono
 
CDNによるInternet支配の現状とICNの可能性
CDNによるInternet支配の現状とICNの可能性CDNによるInternet支配の現状とICNの可能性
CDNによるInternet支配の現状とICNの可能性J-Stream Inc.
 
Android is going to Go! Android and Golang
Android is going to Go! Android and GolangAndroid is going to Go! Android and Golang
Android is going to Go! Android and GolangAlmog Baku
 
Develop Android/iOS app using golang
Develop Android/iOS app using golangDevelop Android/iOS app using golang
Develop Android/iOS app using golangSeongJae Park
 

Viewers also liked (20)

A microservice architecture based on golang
A microservice architecture based on golangA microservice architecture based on golang
A microservice architecture based on golang
 
Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?
 
Write microservice in golang
Write microservice in golangWrite microservice in golang
Write microservice in golang
 
Golang server design pattern
Golang server design patternGolang server design pattern
Golang server design pattern
 
Develop Android app using Golang
Develop Android app using GolangDevelop Android app using Golang
Develop Android app using Golang
 
マイクロサービスバックエンドAPIのためのRESTとgRPC
マイクロサービスバックエンドAPIのためのRESTとgRPCマイクロサービスバックエンドAPIのためのRESTとgRPC
マイクロサービスバックエンドAPIのためのRESTとgRPC
 
ドメインロジックに集中せよ 〜ドメイン駆動設計 powered by Spring
ドメインロジックに集中せよ 〜ドメイン駆動設計 powered by Springドメインロジックに集中せよ 〜ドメイン駆動設計 powered by Spring
ドメインロジックに集中せよ 〜ドメイン駆動設計 powered by Spring
 
Goをカンストさせる話
Goをカンストさせる話Goをカンストさせる話
Goをカンストさせる話
 
Architecting for the Cloud using NetflixOSS - Codemash Workshop
Architecting for the Cloud using NetflixOSS - Codemash WorkshopArchitecting for the Cloud using NetflixOSS - Codemash Workshop
Architecting for the Cloud using NetflixOSS - Codemash Workshop
 
Memory Interoperability in Analytics and Machine Learning
Memory Interoperability in Analytics and Machine LearningMemory Interoperability in Analytics and Machine Learning
Memory Interoperability in Analytics and Machine Learning
 
13 practical tips for writing secure golang applications
13 practical tips for writing secure golang applications13 practical tips for writing secure golang applications
13 practical tips for writing secure golang applications
 
2017年グローバルリクルーティングトレンド / Global Recruiting Trend
2017年グローバルリクルーティングトレンド / Global Recruiting Trend2017年グローバルリクルーティングトレンド / Global Recruiting Trend
2017年グローバルリクルーティングトレンド / Global Recruiting Trend
 
Golang for OO Programmers
Golang for OO ProgrammersGolang for OO Programmers
Golang for OO Programmers
 
並行実行制御の最適化手法
並行実行制御の最適化手法並行実行制御の最適化手法
並行実行制御の最適化手法
 
CDNによるInternet支配の現状とICNの可能性
CDNによるInternet支配の現状とICNの可能性CDNによるInternet支配の現状とICNの可能性
CDNによるInternet支配の現状とICNの可能性
 
Android is going to Go! Android and Golang
Android is going to Go! Android and GolangAndroid is going to Go! Android and Golang
Android is going to Go! Android and Golang
 
Develop Android/iOS app using golang
Develop Android/iOS app using golangDevelop Android/iOS app using golang
Develop Android/iOS app using golang
 
Kameoka2017 ieice03
Kameoka2017 ieice03Kameoka2017 ieice03
Kameoka2017 ieice03
 
Vue.js with Go
Vue.js with GoVue.js with Go
Vue.js with Go
 
go 1.8 net/http timeouts
go 1.8 net/http timeoutsgo 1.8 net/http timeouts
go 1.8 net/http timeouts
 

Similar to Functional go

pure-functional-programming.pdf
pure-functional-programming.pdfpure-functional-programming.pdf
pure-functional-programming.pdfPuneetChaturvedi23
 
Alpine Spark Implementation - Technical
Alpine Spark Implementation - TechnicalAlpine Spark Implementation - Technical
Alpine Spark Implementation - Technicalalpinedatalabs
 
Multinomial Logistic Regression with Apache Spark
Multinomial Logistic Regression with Apache SparkMultinomial Logistic Regression with Apache Spark
Multinomial Logistic Regression with Apache SparkDB Tsai
 
Functional programming in clojure
Functional programming in clojureFunctional programming in clojure
Functional programming in clojureJuan-Manuel Gimeno
 
Reactive cocoa 101
Reactive cocoa 101Reactive cocoa 101
Reactive cocoa 101Hai Feng Kao
 
Inline function
Inline functionInline function
Inline functionTech_MX
 
Intro f# functional_programming
Intro f# functional_programmingIntro f# functional_programming
Intro f# functional_programmingMauro Ghiani
 
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Codemotion
 
DataWeave 2.0 Language Fundamentals
DataWeave 2.0 Language FundamentalsDataWeave 2.0 Language Fundamentals
DataWeave 2.0 Language FundamentalsJoshua Erney
 
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16Innovecs
 
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docxJLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docxvrickens
 

Similar to Functional go (20)

pure-functional-programming.pdf
pure-functional-programming.pdfpure-functional-programming.pdf
pure-functional-programming.pdf
 
Functional programming 101
Functional programming 101Functional programming 101
Functional programming 101
 
Alpine Spark Implementation - Technical
Alpine Spark Implementation - TechnicalAlpine Spark Implementation - Technical
Alpine Spark Implementation - Technical
 
Multinomial Logistic Regression with Apache Spark
Multinomial Logistic Regression with Apache SparkMultinomial Logistic Regression with Apache Spark
Multinomial Logistic Regression with Apache Spark
 
Scala qq
Scala qqScala qq
Scala qq
 
Functional programming in clojure
Functional programming in clojureFunctional programming in clojure
Functional programming in clojure
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Scala functions
Scala functionsScala functions
Scala functions
 
Reactive cocoa 101
Reactive cocoa 101Reactive cocoa 101
Reactive cocoa 101
 
Inline function
Inline functionInline function
Inline function
 
functions
functionsfunctions
functions
 
Intro f# functional_programming
Intro f# functional_programmingIntro f# functional_programming
Intro f# functional_programming
 
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
 
DataWeave 2.0 Language Fundamentals
DataWeave 2.0 Language FundamentalsDataWeave 2.0 Language Fundamentals
DataWeave 2.0 Language Fundamentals
 
Functional programming java
Functional programming javaFunctional programming java
Functional programming java
 
A taste of Functional Programming
A taste of Functional ProgrammingA taste of Functional Programming
A taste of Functional Programming
 
Introductory func prog
Introductory func progIntroductory func prog
Introductory func prog
 
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
 
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docxJLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 

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

Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...Andrea Goulet
 
Lessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdfLessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdfSrushith Repakula
 
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...Lisi Hocke
 
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdfThe Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdfkalichargn70th171
 
Prompt Engineering - an Art, a Science, or your next Job Title?
Prompt Engineering - an Art, a Science, or your next Job Title?Prompt Engineering - an Art, a Science, or your next Job Title?
Prompt Engineering - an Art, a Science, or your next Job Title?Maxim Salnikov
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
^Clinic ^%[+27788225528*Abortion Pills For Sale In sowetokasambamuno
 
Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024Henry Schreiner
 
Jax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined DeckJax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined DeckMarc Lester
 
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-CloudAlluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-CloudAlluxio, Inc.
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfsteffenkarlsson2
 
BusinessGPT - Security and Governance for Generative AI
BusinessGPT  - Security and Governance for Generative AIBusinessGPT  - Security and Governance for Generative AI
BusinessGPT - Security and Governance for Generative AIAGATSoftware
 
Effective Strategies for Wix's Scaling challenges - GeeCon
Effective Strategies for Wix's Scaling challenges - GeeConEffective Strategies for Wix's Scaling challenges - GeeCon
Effective Strategies for Wix's Scaling challenges - GeeConNatan Silnitsky
 
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024SimonedeGijt
 
[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse
[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse
[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypseTomasz Kowalczewski
 
Transformer Neural Network Use Cases with Links
Transformer Neural Network Use Cases with LinksTransformer Neural Network Use Cases with Links
Transformer Neural Network Use Cases with LinksJinanKordab
 
The mythical technical debt. (Brooke, please, forgive me)
The mythical technical debt. (Brooke, please, forgive me)The mythical technical debt. (Brooke, please, forgive me)
The mythical technical debt. (Brooke, please, forgive me)Roberto Bettazzoni
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In witbank
^Clinic ^%[+27788225528*Abortion Pills For Sale In witbank^Clinic ^%[+27788225528*Abortion Pills For Sale In witbank
^Clinic ^%[+27788225528*Abortion Pills For Sale In witbankkasambamuno
 
Automate your OpenSIPS config tests - OpenSIPS Summit 2024
Automate your OpenSIPS config tests - OpenSIPS Summit 2024Automate your OpenSIPS config tests - OpenSIPS Summit 2024
Automate your OpenSIPS config tests - OpenSIPS Summit 2024Andreas Granig
 
Community is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea GouletCommunity is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea GouletAndrea Goulet
 

Recently uploaded (20)

Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
 
Lessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdfLessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdf
 
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
 
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdfThe Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
 
Prompt Engineering - an Art, a Science, or your next Job Title?
Prompt Engineering - an Art, a Science, or your next Job Title?Prompt Engineering - an Art, a Science, or your next Job Title?
Prompt Engineering - an Art, a Science, or your next Job Title?
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
 
Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024
 
Jax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined DeckJax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined Deck
 
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-CloudAlluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
 
BusinessGPT - Security and Governance for Generative AI
BusinessGPT  - Security and Governance for Generative AIBusinessGPT  - Security and Governance for Generative AI
BusinessGPT - Security and Governance for Generative AI
 
Effective Strategies for Wix's Scaling challenges - GeeCon
Effective Strategies for Wix's Scaling challenges - GeeConEffective Strategies for Wix's Scaling challenges - GeeCon
Effective Strategies for Wix's Scaling challenges - GeeCon
 
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024
 
[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse
[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse
[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse
 
Abortion Clinic In Polokwane ](+27832195400*)[ 🏥 Safe Abortion Pills in Polok...
Abortion Clinic In Polokwane ](+27832195400*)[ 🏥 Safe Abortion Pills in Polok...Abortion Clinic In Polokwane ](+27832195400*)[ 🏥 Safe Abortion Pills in Polok...
Abortion Clinic In Polokwane ](+27832195400*)[ 🏥 Safe Abortion Pills in Polok...
 
Transformer Neural Network Use Cases with Links
Transformer Neural Network Use Cases with LinksTransformer Neural Network Use Cases with Links
Transformer Neural Network Use Cases with Links
 
The mythical technical debt. (Brooke, please, forgive me)
The mythical technical debt. (Brooke, please, forgive me)The mythical technical debt. (Brooke, please, forgive me)
The mythical technical debt. (Brooke, please, forgive me)
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In witbank
^Clinic ^%[+27788225528*Abortion Pills For Sale In witbank^Clinic ^%[+27788225528*Abortion Pills For Sale In witbank
^Clinic ^%[+27788225528*Abortion Pills For Sale In witbank
 
Automate your OpenSIPS config tests - OpenSIPS Summit 2024
Automate your OpenSIPS config tests - OpenSIPS Summit 2024Automate your OpenSIPS config tests - OpenSIPS Summit 2024
Automate your OpenSIPS config tests - OpenSIPS Summit 2024
 
Community is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea GouletCommunity is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea Goulet
 

Functional go

  • 2. 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 enfatizes change of state”.
  • 3. 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. Functional Go
  • 4. 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". Functional Go
  • 5. Advantages enabled by referential transparence ● 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. Functional Go
  • 6. Advantages enabled by referential transparence ● Parallelization ○ Functions calls are independent. ○ We can parallelize in different process/CPUs/computers/… We can execute func1 and func2 in paralell because a won’t be modified. result = func1(a, b) + func2(a, c) Functional Go
  • 7. Advantages enabled by referential transparence ● Concurrence a. With no shared data, concurrence gets a lot simpler: i. No semaphores. ii. No monitors. iii. No locks. iv. No race-conditions. v. No dead-locks. Functional Go
  • 8. Golang is a multi paradigm programming language. As a Golang programmer why uses functional programming? Golang is not a functional language but have a lot of features that enables us to applies functional principles in the development, turning our code more elegant, concise, maintanable, easier to understand and test. Functional Go
  • 9. Don’t Update, Create - String name := "Geison" name := name + " Flores" const firstname = "Geison" const lasname = "Flores" const name = firstname + " " + lastname Functional Go
  • 10. Don’t Update, Create - Arrays years := [4]int{2001, 2002} years[2] = 2003 years[3] = 2004 years // [2001, 2002, 2003, 2004] years := [2]{2001, 2001} allYears := append(years, 2003, [2]int{2004, 2005} Functional Go
  • 11. Don’t Update, Create - Maps ages := map[string]int{"John": 30} ages["Mary"] = 28 ages // {'John': 30, 'Mary': 28} Functional Go 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[K]V, len(ages1) + len(ages2)) for k, v := range mapA { allAges[k] = v } for k, v := range mapB { allAges[k] = v } return allAges } allAges := mergeMaps(ages1, ages2)
  • 12. 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(s name) string { return "Hello " + name } caller(f) Functional Go
  • 13. 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("milu", "rantanplan")) //["MILU", "RANTANPLAN"] Functional Go
  • 14. 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] Functional Go
  • 15. 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("milu", "rantanplan"), acumullator, string).(uint64) // result 14 Functional Go
  • 16. 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 Functional Go
  • 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. Functional Go 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 }
  • 18. 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. Functional Go
  • 19. 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. ● Unfortunarely following recursion style in Golang has it’s own tax: Performance. Functional Go
  • 20. Solving Golang Lack of TCO(Tail Call Optimization) // The functional solution have problens with big values func fibonacciRecursive(n int) int { if n <= 1 { return n } return n * fibonacciRecursive(n - 1) } Functional Go
  • 21. 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 } Functional Go
  • 22. FP in OOP? It is possible do FP in OOP? Yes it is! ● OOP is orthogonal to FP. ● Well, at least in theory, because: ○ Typical OOP tends to emphasize change of state in objects. ○ Typical OOP mixes the concepts of identity and state. ○ Mixture of data and code raises both conceptual and practical problems. ● OOP functional languages: Scala, F#, ... Functional Go
  • 23. A Pratical Example Exercise: "What's the sum of the first 10 natural number whose square value is divisible by 5?" Imperative: Functional: func main() { n, numElements, s := 1, 0, 0 for numElements < 10 { if n * n % 5 == 0 { s += n numElements++ } n++ } fmt.Println(s) //275 } Functional Go sum := func (memo interface{}, el interface{}) interface{} { return memo.(float64) + el.(float64) } pred := func (i interface{}) bool { return (i.(uint64) * i.(uint64)) % 5 == 0 } values := make([]int, 100) for num := 1; num <= 100; num++ { values = append(values, num) } Reduce(Filter(pred, values), sum, uint64).(uint64)
  • 24. 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# Functional Go
  • 25. 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. ● Any other thoughts? Functional Go
  • 26. 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 Functional Go
  • 27. Contact me ● Email: ○ geisonfgf@gmail.com ● Skype ○ geisonfgf ● Facebook ○ http://www.facebook.com/geisonfgf ● Twitter ○ http://www.twitter.com/geisonfgf Functional Go