SlideShare a Scribd company logo
What did functional programming ever do for us
(software engineers)?
An extreme pragmatic and un-academic approach
Sergei Winitzki
Academy by the Bay
2020-08-22
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 1 / 18
Overview: Advantages of functional programming
Features of functional programming are being added to many languages
What are these features?
What advantages do they give programmers?
Programmer-facing features listed in the increasing order of complexity
(and decreasing order of advantage-to-cost ratio)
1 Write iterative code without loops
2 Use functions parameterized by types, checked by compiler
3 Use disjunctive types to model special cases, errors, etc.
4 Use special syntax for chaining effectful computations
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 2 / 18
Feature 1: Loop-free iterative programs. Transformation
An easy interview question:
Given an array of integers, find all pairs that sum to a given number
Solutions using loops: 10-20 lines of code
FP solution with O(n2) complexity:
# Python
[ (x, y) for x in array for y in array if x + y == n ]
// Scala
for { x <- array; y <- array; if x + y == n } yield (x, y)
-- Haskell
do; x <- array; y <- array; guard (x + y == n); return (x, y)
FP solution with O(n log n) complexity:
// Scala
val hash = array.toSet
for { x <- hash; if hash contains (n - x) } yield (x, n - x)
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 3 / 18
Feature 1: Loop-free iterative programs. Aggregation
Given an array of integers, compute the sum of square roots of all
elements except negative ones
# Python
sum( [ sqrt(x) for x in givenArray if x >= 0 ] )
// Scala
givenArray.filter(_ >= 0).map(math.sqrt).sum
Given a set of integers, compute the sum of those integers which are
non-negative and whose square root is also present in the set
Solution using loops: 15-20 lines of code
FP solution:
givenSet // Scala
.filter { x => x >= 0 && givenSet.contains(math.sqrt(x)) }
.sum
Compute a positive integer from a given array of its decimal digits
digits.reverse.zipWithIndex // Scala
.map { case (d, i) => d * math.pow(10, i).toInt } .sum
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 4 / 18
Feature 1: Loop-free iterative programs. Induction
Compute the mean value of a given sequence in single pass
scala> Seq(4, 5, 6, 7).foldLeft((0.0, 0.0)) {
| case ((sum, count), x) => (sum + x, count + 1)
| }.pipe { case (sum, count) => sum / count }
res1: Double = 5.5
Any inductive definition can be converted to a “fold”
Base case is the initial value
Inductive step is the updater function
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 5 / 18
Feature 1: Loop-free iterative programs. Other applications
The implementation of map, filter, fold, flatMap, groupBy, sum, etc.,
may be asynchronous (Akka Streams), parallel, and/or distributed
(Spark, Flink)
The programmer writes loop-free code in the map/filter/reduce style
The runtime engine implements parallelism, fault tolerance, etc.
Many types of programmer errors are avoided automatically
What we need to support programming in the map/filter/reduce style:
Collections with user-definable methods
Functions (“lambdas”) passed as parameters to other functions
Easy work with tuple types
Lambdas were added to most programming languages by 2015
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 6 / 18
Feature 2: Type parameters. Usage
Collections can have types parameterized by element type
Array of integers: Array[Int]
Array of strings: Array[String]
Array of arrays of pairs of integers and strings: Array[Array[(Int,
String)]]
Methods such as map, zip, flatMap, groupBy change the type parameters
Seq(4, 5, 6, 7) // Seq[Int]
.zip(Seq("a", "b", "c", "d")) // Seq[(Int, String)]
.map { case (i, s) => s"$s : $i" } // Seq[String]
The compiler prevents using incorrect type parameters anywhere
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 7 / 18
Feature 2: Type parameters. Language features
Code can be written once, then used with different type parameters
Example (Scala):
def map[A, B](xs: Seq[A])(f: A => B): Seq[B] = ...
Collections (Array, Set, etc.) with type parameters support such
methods
Many programming languages have type parameters
Functions with type parameters were added to Java in 2006
C++ can imitate this functionality with templates
Go-lang might get type parameters in the future
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 8 / 18
Feature 3: Disjunctive types
Enumeration type (enum) describes a set of disjoint possibilities:
enum Color { RED, GREEN, BLUE; } // Java
A value of type Color can be only one of the three possibilities
Disjunctive types are “enriched” enum types, carrying extra values:
// Scala 3
enum RootOfEq { case NoRoots(); case OneRoot(x: Float); }
The switch is “enriched” to extract data from disjunctive values
// Scala
roots match {
case OneRoot(x) => // May use ‘x‘ in this expression.
case NoRoots() => // May not use ‘x‘ here by mistake.
}
Disjunctive types describe values from “tagged union” sets
OneRoot(x) ∼= the set of all Float values
NoRoots() ∼= the set consisting of a single value
RootOfEq ∼= either some Float value or the special value NoRoots()
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 9 / 18
Feature 3: Disjunctive types. Adoption in languages
Disjunctive types and pattern matching are required for FP
Introduced in Standard ML (1973)
Supported in all FP languages (OCaml, Haskell, F#, Scala, Swift, ...)
The support of disjunctive types only comes in FP-designed languages
Not supported in C, C++, Java, JavaScript, Python, Go, ...
Not supported in relational languages (Prolog, SQL, Datalog, ...)
Not supported in configuration data formats (XML, JSON, YAML, ...)
Logical completeness of the type system:
Scala type Logic operation Logic notation Type notation
(A, B) conjunction A ∧ B A × B
Either[A, B] disjunction A ∨ B A + B
A => B implication A ⇒ B A → B
Unit true 1
Nothing false ⊥ 0
Programming is easier in languages having a complete logic of types
“Hindley-Milner type system”
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 10 / 18
Feature 4: Chaining of effects. Motivation
How to compose computations that may fail with an error?
A “result or error” disjunctive type: Try[A] ∼= Either[Throwable, A]
In Scala, Try[A] is a disjunction of Failure[Throwable] and Success[A]
Working with Try[A] requires two often-used code patterns:
Use Try[A] in a computation that cannot fail, f: A => B
Success(a) goes to Success(f(a)) but Failure(t) remains unchanged
Use Try[A] in a computation that can fail, g: A => Try[B]
Success(a) goes to g(a) while Failure(t) remains unchanged
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 11 / 18
Feature 4: Chaining of effects. Implementation
Implementing the two code patterns using pattern matching:
Pattern 1: use Try[A] in a computation that cannot fail
tryGetFileStats() match {
case Success(stats) => Success(stats.getTimestamp)
case Failure(exception) => Failure(exception)
}
Pattern 2: use Try[A] in a computation that can fail
tryOpenFile() match {
case Success(file) => tryRead(file) // Returns Try[Array[Byte]]
case Failure(exception) => Failure(exception)
}
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 12 / 18
Feature 4: Chaining of effects. Implementation
The two patterns may be combined at will
// Read a file, decode UTF-8, return the number of chars.
def utfChars(name: String): Try[Int] = tryOpenFile(name) match {
case Success(file) => tryRead(file) match {
case Success(bytes) => tryDecodeUTF8(bytes) match {
case Success(decoded) => Success(decoded.length)
case Failure(exception) => Failure(exception)
}
case Failure(exception) => Failure(exception)
}
case Failure(exception) => Failure(exception)
}
The code is awkwardly nested and repetitive
This sort of code is common in go-lang programs:
err1, res1 := tryOpenFile();
if (res1 != nil) {
err2, res2 := tryRead(res1);
if (res2 != nil) { ... } // Continue with no errors.
else ... // Handle second error.
else ... // Handle first error.
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 13 / 18
Feature 4: Chaining of effects. Using map and flatMap
Implement the two code patterns using map and flatMap:
Try(a).map(f) – use with f: A => B that cannot fail
Try(a).flatMap(g) – use with g: A => Try[B] that can fail
def fmap[A, B](f: A => B): Try[A] => Try[B]
def flm[A, B](g: A => Try[B]): Try[A] => Try[B]
Pattern 1: use Try[A] in a computation that cannot fail
tryGetFileStats() match {
case Success(stats) => Success(stats.getTimestamp)
case Failure(exception) => Failure(exception)
}
Pattern 2: use Try[A] in a computation that can fail
tryOpenFile() match {
case Success(file) => read(file) // Returns Try[InputStream]
case Failure(exception) => Failure(exception)
}
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 14 / 18
Feature 4: Chaining of effects. Special syntax
Using map and flatMap, the code from the previous slide simplifies:
tryGetFileStats().map(stats => stats.getTimestamp)
tryOpenFile().flatMap(file => read(file))
We can now write code like this (avoiding nesting and repetition):
Try(one()).map { x => f(x) }.flatMap { y => Try(another(y)) }
Instead of a chain of map and flatMap methods, use a special syntax:
for {
x <- Try(one())
y = f(x)
z <- Try(another(y))
} yield z
Resembles the syntax for nested loops (“for-comprehension”)
for { x <- list1; y <- list2 } yield p(x, y) // Scala
[ p(x, y) for y in list2 for x in list1 ] // Python
In Haskell: “do notation”, in F#: “computation expressions”
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 15 / 18
Feature 4: Chaining of effects. Special syntax
Using the special syntax, a chain of computations looks like this:
// Read a file, decode UTF-8, return the number of chars.
def utfChars(name: String): Try[Int] = for {
file <- tryOpenFile(name)
bytes <- tryRead(file)
decoded <- tryDecodeUTF8(bytes)
length = decoded.length
} yield length
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 16 / 18
Features 1-4 may be combined at will
The main advantages in practical coding come from combining features 1-4
of functional programming
Use functional methods on collections with type parameters
Use disjunctive types to represent program requirements
Avoid explicit loops and make sure all types match
Compose programs at high level by chaining effects (Try, Future, ...)
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 17 / 18
Summary
FP proposes 4 essential features that make programming easier
loop-free iteration, type parameters, disjunctive types, chaining syntax
other, more advanced features have lower cost/advantage ratios
All “FP languages” have these features and give the same advantages
OCaml, Haskell, Scala, F#, Swift, Rust, Elm, ...
Most “non-FP languages” lack at least 2 of these features
Lack of features may be compensated but raises the cost of their use
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 18 / 18

More Related Content

What's hot

Evaluation of postfix expression
Evaluation of postfix expressionEvaluation of postfix expression
Evaluation of postfix expression
Akhil Ahuja
 
Stack data structure
Stack data structureStack data structure
Stack data structureTech_MX
 
Unit 3 stack
Unit   3 stackUnit   3 stack
Unit 3 stack
Dabbal Singh Mahara
 
stack
stackstack
stack
Raj Sarode
 
Conversion of Infix To Postfix Expressions
Conversion of Infix To Postfix Expressions Conversion of Infix To Postfix Expressions
Conversion of Infix To Postfix Expressions
Kulachi Hansraj Model School Ashok Vihar
 
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Brendan Eich
 
Value objects in JS - an ES7 work in progress
Value objects in JS - an ES7 work in progressValue objects in JS - an ES7 work in progress
Value objects in JS - an ES7 work in progress
Brendan Eich
 
Extensible Operators and Literals for JavaScript
Extensible Operators and Literals for JavaScriptExtensible Operators and Literals for JavaScript
Extensible Operators and Literals for JavaScript
Brendan Eich
 
3 operators-expressions-and-statements-120712073351-phpapp01
3 operators-expressions-and-statements-120712073351-phpapp013 operators-expressions-and-statements-120712073351-phpapp01
3 operators-expressions-and-statements-120712073351-phpapp01Abdul Samee
 
answer-model-qp-15-pcd13pcd
answer-model-qp-15-pcd13pcdanswer-model-qp-15-pcd13pcd
answer-model-qp-15-pcd13pcd
Syed Mustafa
 
김재석, C++ 프로그래머를 위한 C#, NDC2011
김재석, C++ 프로그래머를 위한 C#, NDC2011김재석, C++ 프로그래머를 위한 C#, NDC2011
김재석, C++ 프로그래머를 위한 C#, NDC2011devCAT Studio, NEXON
 
Aspect-Oriented Technologies
Aspect-Oriented TechnologiesAspect-Oriented Technologies
Aspect-Oriented Technologies
Esteban Abait
 
Debugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template MetaprogramsDebugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template Metaprograms
Platonov Sergey
 

What's hot (13)

Evaluation of postfix expression
Evaluation of postfix expressionEvaluation of postfix expression
Evaluation of postfix expression
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
Unit 3 stack
Unit   3 stackUnit   3 stack
Unit 3 stack
 
stack
stackstack
stack
 
Conversion of Infix To Postfix Expressions
Conversion of Infix To Postfix Expressions Conversion of Infix To Postfix Expressions
Conversion of Infix To Postfix Expressions
 
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
 
Value objects in JS - an ES7 work in progress
Value objects in JS - an ES7 work in progressValue objects in JS - an ES7 work in progress
Value objects in JS - an ES7 work in progress
 
Extensible Operators and Literals for JavaScript
Extensible Operators and Literals for JavaScriptExtensible Operators and Literals for JavaScript
Extensible Operators and Literals for JavaScript
 
3 operators-expressions-and-statements-120712073351-phpapp01
3 operators-expressions-and-statements-120712073351-phpapp013 operators-expressions-and-statements-120712073351-phpapp01
3 operators-expressions-and-statements-120712073351-phpapp01
 
answer-model-qp-15-pcd13pcd
answer-model-qp-15-pcd13pcdanswer-model-qp-15-pcd13pcd
answer-model-qp-15-pcd13pcd
 
김재석, C++ 프로그래머를 위한 C#, NDC2011
김재석, C++ 프로그래머를 위한 C#, NDC2011김재석, C++ 프로그래머를 위한 C#, NDC2011
김재석, C++ 프로그래머를 위한 C#, NDC2011
 
Aspect-Oriented Technologies
Aspect-Oriented TechnologiesAspect-Oriented Technologies
Aspect-Oriented Technologies
 
Debugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template MetaprogramsDebugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template Metaprograms
 

Similar to Functional programming-advantages

Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningCarol McDonald
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
JAXLondon_Conference
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
Roberto Casadei
 
Applying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedApplying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing Speed
Pascal-Louis Perez
 
Java 8
Java 8Java 8
Java 8
vilniusjug
 
Designing Architecture-aware Library using Boost.Proto
Designing Architecture-aware Library using Boost.ProtoDesigning Architecture-aware Library using Boost.Proto
Designing Architecture-aware Library using Boost.Proto
Joel Falcou
 
Java parallel programming made simple
Java parallel programming made simpleJava parallel programming made simple
Java parallel programming made simple
Ateji Px
 
Data Structures problems 2002
Data Structures problems 2002Data Structures problems 2002
Data Structures problems 2002
Sanjay Goel
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
daewon jeong
 
Automatic Task-based Code Generation for High Performance DSEL
Automatic Task-based Code Generation for High Performance DSELAutomatic Task-based Code Generation for High Performance DSEL
Automatic Task-based Code Generation for High Performance DSEL
Joel Falcou
 
TI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific LanguagesTI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific LanguagesEelco Visser
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
Martin Odersky
 
Golang dot-testing-lite
Golang dot-testing-liteGolang dot-testing-lite
Golang dot-testing-lite
Richárd Kovács
 
SCALA - Functional domain
SCALA -  Functional domainSCALA -  Functional domain
SCALA - Functional domain
Bartosz Kosarzycki
 
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021
Peng Cheng
 
Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)
Hermann Hueck
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its API
Jörn Guy Süß JGS
 
2. data, operators, io
2. data, operators, io2. data, operators, io
2. data, operators, io
Srichandan Sobhanayak
 

Similar to Functional programming-advantages (20)

Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
 
Applying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedApplying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing Speed
 
Java 8
Java 8Java 8
Java 8
 
Designing Architecture-aware Library using Boost.Proto
Designing Architecture-aware Library using Boost.ProtoDesigning Architecture-aware Library using Boost.Proto
Designing Architecture-aware Library using Boost.Proto
 
Java parallel programming made simple
Java parallel programming made simpleJava parallel programming made simple
Java parallel programming made simple
 
Data Structures problems 2002
Data Structures problems 2002Data Structures problems 2002
Data Structures problems 2002
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
Automatic Task-based Code Generation for High Performance DSEL
Automatic Task-based Code Generation for High Performance DSELAutomatic Task-based Code Generation for High Performance DSEL
Automatic Task-based Code Generation for High Performance DSEL
 
TI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific LanguagesTI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific Languages
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Golang dot-testing-lite
Golang dot-testing-liteGolang dot-testing-lite
Golang dot-testing-lite
 
SCALA - Functional domain
SCALA -  Functional domainSCALA -  Functional domain
SCALA - Functional domain
 
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021
 
Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its API
 
cp05.pptx
cp05.pptxcp05.pptx
cp05.pptx
 
2. data, operators, io
2. data, operators, io2. data, operators, io
2. data, operators, io
 

Recently uploaded

Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
Srikant77
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 

Recently uploaded (20)

Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 

Functional programming-advantages

  • 1. What did functional programming ever do for us (software engineers)? An extreme pragmatic and un-academic approach Sergei Winitzki Academy by the Bay 2020-08-22 Sergei Winitzki (ABTB) Why functional programming 2020-08-22 1 / 18
  • 2. Overview: Advantages of functional programming Features of functional programming are being added to many languages What are these features? What advantages do they give programmers? Programmer-facing features listed in the increasing order of complexity (and decreasing order of advantage-to-cost ratio) 1 Write iterative code without loops 2 Use functions parameterized by types, checked by compiler 3 Use disjunctive types to model special cases, errors, etc. 4 Use special syntax for chaining effectful computations Sergei Winitzki (ABTB) Why functional programming 2020-08-22 2 / 18
  • 3. Feature 1: Loop-free iterative programs. Transformation An easy interview question: Given an array of integers, find all pairs that sum to a given number Solutions using loops: 10-20 lines of code FP solution with O(n2) complexity: # Python [ (x, y) for x in array for y in array if x + y == n ] // Scala for { x <- array; y <- array; if x + y == n } yield (x, y) -- Haskell do; x <- array; y <- array; guard (x + y == n); return (x, y) FP solution with O(n log n) complexity: // Scala val hash = array.toSet for { x <- hash; if hash contains (n - x) } yield (x, n - x) Sergei Winitzki (ABTB) Why functional programming 2020-08-22 3 / 18
  • 4. Feature 1: Loop-free iterative programs. Aggregation Given an array of integers, compute the sum of square roots of all elements except negative ones # Python sum( [ sqrt(x) for x in givenArray if x >= 0 ] ) // Scala givenArray.filter(_ >= 0).map(math.sqrt).sum Given a set of integers, compute the sum of those integers which are non-negative and whose square root is also present in the set Solution using loops: 15-20 lines of code FP solution: givenSet // Scala .filter { x => x >= 0 && givenSet.contains(math.sqrt(x)) } .sum Compute a positive integer from a given array of its decimal digits digits.reverse.zipWithIndex // Scala .map { case (d, i) => d * math.pow(10, i).toInt } .sum Sergei Winitzki (ABTB) Why functional programming 2020-08-22 4 / 18
  • 5. Feature 1: Loop-free iterative programs. Induction Compute the mean value of a given sequence in single pass scala> Seq(4, 5, 6, 7).foldLeft((0.0, 0.0)) { | case ((sum, count), x) => (sum + x, count + 1) | }.pipe { case (sum, count) => sum / count } res1: Double = 5.5 Any inductive definition can be converted to a “fold” Base case is the initial value Inductive step is the updater function Sergei Winitzki (ABTB) Why functional programming 2020-08-22 5 / 18
  • 6. Feature 1: Loop-free iterative programs. Other applications The implementation of map, filter, fold, flatMap, groupBy, sum, etc., may be asynchronous (Akka Streams), parallel, and/or distributed (Spark, Flink) The programmer writes loop-free code in the map/filter/reduce style The runtime engine implements parallelism, fault tolerance, etc. Many types of programmer errors are avoided automatically What we need to support programming in the map/filter/reduce style: Collections with user-definable methods Functions (“lambdas”) passed as parameters to other functions Easy work with tuple types Lambdas were added to most programming languages by 2015 Sergei Winitzki (ABTB) Why functional programming 2020-08-22 6 / 18
  • 7. Feature 2: Type parameters. Usage Collections can have types parameterized by element type Array of integers: Array[Int] Array of strings: Array[String] Array of arrays of pairs of integers and strings: Array[Array[(Int, String)]] Methods such as map, zip, flatMap, groupBy change the type parameters Seq(4, 5, 6, 7) // Seq[Int] .zip(Seq("a", "b", "c", "d")) // Seq[(Int, String)] .map { case (i, s) => s"$s : $i" } // Seq[String] The compiler prevents using incorrect type parameters anywhere Sergei Winitzki (ABTB) Why functional programming 2020-08-22 7 / 18
  • 8. Feature 2: Type parameters. Language features Code can be written once, then used with different type parameters Example (Scala): def map[A, B](xs: Seq[A])(f: A => B): Seq[B] = ... Collections (Array, Set, etc.) with type parameters support such methods Many programming languages have type parameters Functions with type parameters were added to Java in 2006 C++ can imitate this functionality with templates Go-lang might get type parameters in the future Sergei Winitzki (ABTB) Why functional programming 2020-08-22 8 / 18
  • 9. Feature 3: Disjunctive types Enumeration type (enum) describes a set of disjoint possibilities: enum Color { RED, GREEN, BLUE; } // Java A value of type Color can be only one of the three possibilities Disjunctive types are “enriched” enum types, carrying extra values: // Scala 3 enum RootOfEq { case NoRoots(); case OneRoot(x: Float); } The switch is “enriched” to extract data from disjunctive values // Scala roots match { case OneRoot(x) => // May use ‘x‘ in this expression. case NoRoots() => // May not use ‘x‘ here by mistake. } Disjunctive types describe values from “tagged union” sets OneRoot(x) ∼= the set of all Float values NoRoots() ∼= the set consisting of a single value RootOfEq ∼= either some Float value or the special value NoRoots() Sergei Winitzki (ABTB) Why functional programming 2020-08-22 9 / 18
  • 10. Feature 3: Disjunctive types. Adoption in languages Disjunctive types and pattern matching are required for FP Introduced in Standard ML (1973) Supported in all FP languages (OCaml, Haskell, F#, Scala, Swift, ...) The support of disjunctive types only comes in FP-designed languages Not supported in C, C++, Java, JavaScript, Python, Go, ... Not supported in relational languages (Prolog, SQL, Datalog, ...) Not supported in configuration data formats (XML, JSON, YAML, ...) Logical completeness of the type system: Scala type Logic operation Logic notation Type notation (A, B) conjunction A ∧ B A × B Either[A, B] disjunction A ∨ B A + B A => B implication A ⇒ B A → B Unit true 1 Nothing false ⊥ 0 Programming is easier in languages having a complete logic of types “Hindley-Milner type system” Sergei Winitzki (ABTB) Why functional programming 2020-08-22 10 / 18
  • 11. Feature 4: Chaining of effects. Motivation How to compose computations that may fail with an error? A “result or error” disjunctive type: Try[A] ∼= Either[Throwable, A] In Scala, Try[A] is a disjunction of Failure[Throwable] and Success[A] Working with Try[A] requires two often-used code patterns: Use Try[A] in a computation that cannot fail, f: A => B Success(a) goes to Success(f(a)) but Failure(t) remains unchanged Use Try[A] in a computation that can fail, g: A => Try[B] Success(a) goes to g(a) while Failure(t) remains unchanged Sergei Winitzki (ABTB) Why functional programming 2020-08-22 11 / 18
  • 12. Feature 4: Chaining of effects. Implementation Implementing the two code patterns using pattern matching: Pattern 1: use Try[A] in a computation that cannot fail tryGetFileStats() match { case Success(stats) => Success(stats.getTimestamp) case Failure(exception) => Failure(exception) } Pattern 2: use Try[A] in a computation that can fail tryOpenFile() match { case Success(file) => tryRead(file) // Returns Try[Array[Byte]] case Failure(exception) => Failure(exception) } Sergei Winitzki (ABTB) Why functional programming 2020-08-22 12 / 18
  • 13. Feature 4: Chaining of effects. Implementation The two patterns may be combined at will // Read a file, decode UTF-8, return the number of chars. def utfChars(name: String): Try[Int] = tryOpenFile(name) match { case Success(file) => tryRead(file) match { case Success(bytes) => tryDecodeUTF8(bytes) match { case Success(decoded) => Success(decoded.length) case Failure(exception) => Failure(exception) } case Failure(exception) => Failure(exception) } case Failure(exception) => Failure(exception) } The code is awkwardly nested and repetitive This sort of code is common in go-lang programs: err1, res1 := tryOpenFile(); if (res1 != nil) { err2, res2 := tryRead(res1); if (res2 != nil) { ... } // Continue with no errors. else ... // Handle second error. else ... // Handle first error. Sergei Winitzki (ABTB) Why functional programming 2020-08-22 13 / 18
  • 14. Feature 4: Chaining of effects. Using map and flatMap Implement the two code patterns using map and flatMap: Try(a).map(f) – use with f: A => B that cannot fail Try(a).flatMap(g) – use with g: A => Try[B] that can fail def fmap[A, B](f: A => B): Try[A] => Try[B] def flm[A, B](g: A => Try[B]): Try[A] => Try[B] Pattern 1: use Try[A] in a computation that cannot fail tryGetFileStats() match { case Success(stats) => Success(stats.getTimestamp) case Failure(exception) => Failure(exception) } Pattern 2: use Try[A] in a computation that can fail tryOpenFile() match { case Success(file) => read(file) // Returns Try[InputStream] case Failure(exception) => Failure(exception) } Sergei Winitzki (ABTB) Why functional programming 2020-08-22 14 / 18
  • 15. Feature 4: Chaining of effects. Special syntax Using map and flatMap, the code from the previous slide simplifies: tryGetFileStats().map(stats => stats.getTimestamp) tryOpenFile().flatMap(file => read(file)) We can now write code like this (avoiding nesting and repetition): Try(one()).map { x => f(x) }.flatMap { y => Try(another(y)) } Instead of a chain of map and flatMap methods, use a special syntax: for { x <- Try(one()) y = f(x) z <- Try(another(y)) } yield z Resembles the syntax for nested loops (“for-comprehension”) for { x <- list1; y <- list2 } yield p(x, y) // Scala [ p(x, y) for y in list2 for x in list1 ] // Python In Haskell: “do notation”, in F#: “computation expressions” Sergei Winitzki (ABTB) Why functional programming 2020-08-22 15 / 18
  • 16. Feature 4: Chaining of effects. Special syntax Using the special syntax, a chain of computations looks like this: // Read a file, decode UTF-8, return the number of chars. def utfChars(name: String): Try[Int] = for { file <- tryOpenFile(name) bytes <- tryRead(file) decoded <- tryDecodeUTF8(bytes) length = decoded.length } yield length Sergei Winitzki (ABTB) Why functional programming 2020-08-22 16 / 18
  • 17. Features 1-4 may be combined at will The main advantages in practical coding come from combining features 1-4 of functional programming Use functional methods on collections with type parameters Use disjunctive types to represent program requirements Avoid explicit loops and make sure all types match Compose programs at high level by chaining effects (Try, Future, ...) Sergei Winitzki (ABTB) Why functional programming 2020-08-22 17 / 18
  • 18. Summary FP proposes 4 essential features that make programming easier loop-free iteration, type parameters, disjunctive types, chaining syntax other, more advanced features have lower cost/advantage ratios All “FP languages” have these features and give the same advantages OCaml, Haskell, Scala, F#, Swift, Rust, Elm, ... Most “non-FP languages” lack at least 2 of these features Lack of features may be compensated but raises the cost of their use Sergei Winitzki (ABTB) Why functional programming 2020-08-22 18 / 18