SlideShare una empresa de Scribd logo
1 de 29
Descargar para leer sin conexión
Functional Scala
The Math Connection: From Functions to Free Monads
https://github.com/ReactivePatterns/functional-scala
Functional Ingredients
The Math Connection
• Functions
• Higher Order Functions (chaining with map, reduce, etc.)
• For-Comprehensions
• Monads (chainable computation steps)
• Algebraic DataTypes (functional APIs)
• Free Monads (interpreters)
Basic Scala Concepts
• 3 fundamental building blocks: expressions, values, types
• Valid expressions have a type and calculate a value
• Literals are the simplest expressions
• Blocks are compound expressions built with operators and flow control
expressions (e.g. conditionals)
• Expressions can be pure or can have side-effects
• Every value is an object
• Reusability support: value declarations, functions, methods
• Programs are built from the building blocks (abstractions and reusability are not
required and often avoided)
Basic Functional Ingredients
Scala Math
Function
f: A => B
A and B are types
f: A → B
A and B are sets
HOF
List[A] method:
map[B](f: A => B): List[A]
{f(a) | a ∈ A}
Generalizes to objects in categories
Sequence
Comprehension
for (i <- List.range(0, 20) if i % 2 == 0) yield i
List(0, 2, 4, 6, 8, 10, 12, 14, 16, 18)
{i | i ∈ ℕ, 0 ≤ i < 20, i ≡ 0 (mod 2)}
For
Comprehension
for {
i <- 0 until 20;
j <- i until 20 if i + j == 32
} yield Pair(i, j);
(13, 19)
(14, 18)
(15, 17)
(16, 16)
{(i, j) | i, j ∈ ℕ, 0 ≤ i, j < 20, i + j = 32}
Sequential Computation
1. What comes next?
• 1, 3, 5, 7, ?
• 0, 1, 1, 2, 3, 5, ?
2. Steps can be ordered linearly or as a (directed acyclic)
graph
3. Steps can be: expressions, functions, abstractions
4. Each step represents or produces a value
Example:AlexaVolume API
level
Volume
level: Int
Volume[Int]
level: Double
Volume[Double]
f
flatMap(f)
Unit, FlatMap, Map and
For-Comprehensions
level: Int
Volume[Int]
level: Double
Volume[Double]
f
map(f)
level
Volume
level
Volume
f
flatMap(unit(f))
unit(f)
unit
Flatten
level: A
Volume[A]
level: A
Volume[A]
f
flatMap(f)
Volume[Volume[A]]
map(f)
flatten
Compose
level: A
Volume[A]
level: B
Volume[B]
f
flatMap(f)
level: C
Volume[C]
g
flatMap(g)
Monads
Three elements:
1. Type constructor F[_] that takes one argument (e.g. List, Function0, Option, Either,
Future)
2. A monadic unit, a function that takes a value of any type A and produces a value of
type F[A]

3. A monadic composition operation that takes a function of type A => F[B], and a
function of type B => F[C] and produces a function of type A => F[C]
Two laws:
1. Identity: compose(unit, f) = f = compose(f, unit)
2. Associativity: compose(compose(f, g), h) = compose(f, compose(g, h))
Example: Statistical Distributions
sample
Distribution
DiceThrowing As a Computation
The Monty Hall Problem
to switch or
not to switch?
Monty Hall Problem As a
Computation
vs
Functional Derivation of
Distributions
Existing Monad Implementations
• Cats
• Scalaz
• Akka Agents
• Observable
• Unfortunately NOT Akka Streams
API Functional Design
• Behavior +Types = Algebra
• Return abstractions (monadic types likeTry, Either,
Future, Observable, etc.)
Railway Oriented Programming
Designing For Failure
Implementation
• Functions are lifted to monadic steps (could do that automatically, a topic for another talk)
• State can be managed in a functional manner too (a topic for another talk)
For-Comprehensions or Direct FlatMaps
Allow Step Sequencing/Composition
Future BasedVersion
Akka Agents are used to manage state
HTTP Endpoint
Contracts as UnionTypes
ADT = Algebraic Data Type
Free Monads as Interpreters
• represent stateful computations as data, and run them
• run recursive computations in a stack-safe way
• build an embedded DSL (domain-specific language)
• retarget a computation to another interpreter using
natural transformations
https://github.com/typelevel/cats/blob/master/docs/src/main/tut/freemonad.md
Free API
Write a sequence of instructions in the embedded DSL as a "program",
compile the "program", and finally execute the "program" to interact with
the actual key-value store.
Interpreters/Compilers
Dependency Injection done right
Logic is Passed to Interpreters
Structure, interpretation and execution are separate concerns
AdvancedTopic: Lifting Functions
Two Instructions Are Enough
Summary and Conclusions
• Abstractions give an unfair advantage
• Map and FlatMap are sometimes enough
• Composition through For-Comprehensions is readily
available
• Standardizing computation steps pays big
• Functions are enough as building blocks (they can be
lifted to objects, actors, etc.)

Más contenido relacionado

La actualidad más candente

Lab view introduction-threehour
Lab view introduction-threehourLab view introduction-threehour
Lab view introduction-threehour
e-LabVIEW
 

La actualidad más candente (19)

Lesson 4.1 completing the problem solving process
Lesson 4.1 completing the problem solving processLesson 4.1 completing the problem solving process
Lesson 4.1 completing the problem solving process
 
Lesson 3.2 data types for memory location
Lesson 3.2 data types for memory locationLesson 3.2 data types for memory location
Lesson 3.2 data types for memory location
 
Lesson 5.2 logical operators
Lesson 5.2 logical operatorsLesson 5.2 logical operators
Lesson 5.2 logical operators
 
Matlab - Introduction and Basics
Matlab - Introduction and BasicsMatlab - Introduction and Basics
Matlab - Introduction and Basics
 
details of labviews
details of labviewsdetails of labviews
details of labviews
 
Chapter 2 Basics of MATLAB
Chapter 2 Basics of MATLABChapter 2 Basics of MATLAB
Chapter 2 Basics of MATLAB
 
Typeclass
TypeclassTypeclass
Typeclass
 
Labview pdf
Labview pdfLabview pdf
Labview pdf
 
Lesson 1 introduction to programming
Lesson 1 introduction to programmingLesson 1 introduction to programming
Lesson 1 introduction to programming
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
 
Lab view introduction-threehour
Lab view introduction-threehourLab view introduction-threehour
Lab view introduction-threehour
 
9781285852744 ppt ch16
9781285852744 ppt ch169781285852744 ppt ch16
9781285852744 ppt ch16
 
Lesson 13 object and class
Lesson 13 object and classLesson 13 object and class
Lesson 13 object and class
 
Machine learning on streams of data
Machine learning on streams of dataMachine learning on streams of data
Machine learning on streams of data
 
9781285852744 ppt ch12
9781285852744 ppt ch129781285852744 ppt ch12
9781285852744 ppt ch12
 
Linked list
Linked listLinked list
Linked list
 
9781285852744 ppt ch08
9781285852744 ppt ch089781285852744 ppt ch08
9781285852744 ppt ch08
 
Map algebra
Map algebraMap algebra
Map algebra
 
9781285852744 ppt ch10
9781285852744 ppt ch109781285852744 ppt ch10
9781285852744 ppt ch10
 

Similar a Functional Scala

An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
Adam Getchell
 
Programming in python
Programming in pythonProgramming in python
Programming in python
Ivan Rojas
 

Similar a Functional Scala (20)

Inroduction to r
Inroduction to rInroduction to r
Inroduction to r
 
Java 8
Java 8Java 8
Java 8
 
Matlab Introduction
Matlab IntroductionMatlab Introduction
Matlab Introduction
 
Fuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingFuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional Programming
 
Big data shim
Big data shimBig data shim
Big data shim
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
Algebraic Thinking for Evolution of Pure Functional Domain Models
Algebraic Thinking for Evolution of Pure Functional Domain ModelsAlgebraic Thinking for Evolution of Pure Functional Domain Models
Algebraic Thinking for Evolution of Pure Functional Domain Models
 
Programming in python
Programming in pythonProgramming in python
Programming in python
 
Java 8 streams
Java 8 streams Java 8 streams
Java 8 streams
 
Summer training matlab
Summer training matlab Summer training matlab
Summer training matlab
 
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
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
 
Computer programming and utilization
Computer programming and utilizationComputer programming and utilization
Computer programming and utilization
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
Compiler gate question key
Compiler gate question keyCompiler gate question key
Compiler gate question key
 
Summer training matlab
Summer training matlab Summer training matlab
Summer training matlab
 
Functional Programming.pptx
Functional Programming.pptxFunctional Programming.pptx
Functional Programming.pptx
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
arrays.ppt
arrays.pptarrays.ppt
arrays.ppt
 

Último

%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 

Último (20)

%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
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...
 
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-...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 

Functional Scala