SlideShare a Scribd company logo
1 of 35
Download to read offline
Streams for
(Co)Free!JohnA. De Goes — @jdegoes
Agenda
» Induction/Coinduction
» Universality of Streams
» Cofree: A Principled Stream
» Challenge
InductionTear downastructureto culminate in
aterminalvalue.
Inductive Programs
Examples
» Parse a config file
» Sort a list
» Send an HTTP response
» Compute the millionth digit of pi
Surprise!
Most(?)BusinessProblemsAre
Coinductive
CoinductionStartfroman initialvalueto build up
an infinite structure.
Coinductive Processes
Examples
» Produce the next state of the UI given a user-
input
» Produce current state of config given update to
config
» Transform stream of requests to responses
» Produce (all) the digits of pi
Programming Languages
Hate Coinduction
But"Reactive"and "Streams"
ByAnyOther Name
Astream isamainstream example ofacoinductive process.
» Data processing
» Web servers
» User-interfaces
» Discrete "FRP"
» So much more...
Streams
✓ Stateful
✓ Incremental computation
✓ Non-termination
✓ Consume & Emit
Streams
Choices, Choices
» Akka Streams
» Java Streams
» Scalaz-Streams
» FS2
» Big Data: Spark, Flink, Pachyderm, Kafka, ad
infinitum...
John's Laws ofClean FunctionalCode
1.Reasonability is directly proportional to totality &
referential-transparency.
2.Composability is inversely proportional to number of data
types.
3.Obfuscation is directly proportional to number of lawless
interfaces.
4.Correctness is directly proportional to degree of
parametric polymorphism.
5.Shoddiness is directly proportional to encapsulation.
6.Volume is inversely proportional to orthogonality.
AkkaStream
akka.stream
AbruptTerminationException AbstractShape ActorAttributes ActorMaterializer
ActorMaterializerSettings AmorphousShape Attributes BidiShape BindFailedException
BufferOverflowException Client ClosedShape ConnectionException DelayOverflowStrategy EagerClose
FanInShape FanInShape10 FanInShape11 FanInShape12 FanInShape13 FanInShape14 FanInShape15
FanInShape16 FanInShape17 FanInShape18 FanInShape19 FanInShape1N FanInShape2 FanInShape20
FanInShape21 FanInShape22 FanInShape3 FanInShape4 FanInShape5 FanInShape6 FanInShape7
FanInShape8 FanInShape9 FanOutShape FanOutShape10 FanOutShape11 FanOutShape12 FanOutShape13
FanOutShape14 FanOutShape15 FanOutShape16 FanOutShape17 FanOutShape18 FanOutShape19 FanOutShape2
FanOutShape20 FanOutShape21 FanOutShape22 FanOutShape3 FanOutShape4 FanOutShape5 FanOutShape6
FanOutShape7 FanOutShape8 FanOutShape9 FlowMonitor FlowMonitorState FlowShape Fusing Graph
IgnoreBoth IgnoreCancel IgnoreComplete Inlet InPort IOResult KillSwitch KillSwitches
MaterializationContext MaterializationException Materializer MaterializerLoggingProvider Outlet
OutPort OverflowStrategy QueueOfferResult RateExceededException Server Shape SharedKillSwitch
SinkShape SourceShape StreamLimitReachedException StreamSubscriptionTimeoutSettings
StreamSubscriptionTimeoutTerminationMode StreamTcpException SubstreamCancelStrategy Supervision
ThrottleMode TLSClientAuth TLSClosing TLSProtocol TLSRole UniformFanInShape UniformFanOutShape
UniqueKillSwitch
WhatCan Save Us?!?
John's Laws ofClean FunctionalCode
1.Reasonability is directly proportional to totality &
referential-transparency.
2.Composability is inversely proportional to number of data
types.
3.Obfuscation is directly proportional to number of lawless
interfaces.
4.Correctness is directly proportional to degree of polymorphism.
5.Shoddiness is directly proportional to encapsulation.
6.Volume is inversely proportional to orthogonality.
CofreeALLTHE POWER OFFREE, NOWWITH
STREAMING!!!
Cofree
Huh?
// For Functor `F`
final case class Cofree[F[_], A](head: A, tail: F[Cofree[F, A]])
Cofree:Take 1Cofree[F,A] isacoinductive process
thatgenerates A's using effect F.
Cofree:Take 2Cofree[F,A] isacurrentposition A ona
landscapethatrequires effect Fto
movetoanewposition.
Cofree
Comonad Methods
» Where am I? def extract(f: Cofree[F, A]): A
» Terraform! def extend(f: Cofree[F, A] => B):
Cofree[F, B]
» Plus Functor!
Cofree
Fibs
final case class Cofree[F[_], A](head: A, tail: F[Cofree[F, A]])
// final case class Name[A](run: => A)
val fibs: Cofree[Name, Int] = {
def unfold(prev1: Int, prev2: Int): Cofree[Name, Int] =
Cofree(prev1 + prev2, Name(unfold(prev2, prev1 + prev2)))
unfold(0, 1)
}
Cofree
Append
def append[F[_]: ApplicativePlus, A](c1: Cofree[F, A], c2: Cofree[F, A]): Cofree[F, A] =
Cofree(c1.head, c1.tail.map(t => append(t, c2)) <+> c2.point[F])
Cofree
Collect/Disperse
def collect[F[_]: MonadPlus, A](c: Cofree[F, A]): F[Vector[A]] = {
val singleton = Vector[A](c.head).point[F]
(singleton |@| c.tail.flatMap(collect(_)))(_ ++ _) <+> singleton
}
def disperse[F[_]: ApplicativePlus, A](seq: Seq[A]): Option[Cofree[F, A]] =
seq.foldRight[Option[Cofree[F, A]]](None) {
case (a, None) => Some(Cofree(a, mempty[F, Cofree[F, A]]))
case (a, Some(tail)) => Some(Cofree(a, tail.point[F]))
}
Cofree
Zip
def zipWith[F[_]: Zip: Functor, A, B, C](
c1: Cofree[F, A], c2: Cofree[F, B])(
f: (A, B) => C): Cofree[F, C] =
Cofree(
f(c1.head, c2.head),
Zip[F].zipWith(c1.tail, c2.tail)(zipWith(_, _)(f)))
Cofree
Scan
def scan[F[_]: Functor, A, S](
c: Cofree[F, A])(s: S)(f: (S, A) => S): Cofree[F, S] = {
val s2 = f(s, c.head)
Cofree(s2, c.tail.map(scan(_)(s2)(f)))
}
Cofree
Filter
def zeros[F[_]: Functor, A: Monoid](c: Cofree[F, A])(p: A => Boolean): Cofree[F, A] =
if (p(c.head)) Cofree(c.head, c.tail.map(zeros(_)(p)))
else Cofree(mzero[A], c.tail.map(zeros(_)(p)))
def filter[F[_]: Monad, A](c: Cofree[F, A])(p: A => Boolean): F[Cofree[F, A]] =
if (p(c.head)) Cofree(c.head, c.tail.flatMap(filter(_)(p))).point[F]
else c.tail.flatMap(filter(_)(p))
Cofree
Pipes:Types
// final case class Kleisli[F[_], A, B](run: A => F[B])
type Pipe[F[_], A, B] = Cofree[Kleisli[F, A, ?], B]
type Source[F[_], A] = Pipe[F, Unit, A]
type Sink[F[_], A] = Pipe[F, A, Unit]
Cofree
Pipes: Utilities
def pipe[F[_]: Applicative, A, B, C](from: Pipe[F, A, B], to: Pipe[F, B, C]): Pipe[F, A, C] =
Cofree[Kleisli[F, A, ?], C](
to.head,
Kleisli(a => (from.tail.run(a) |@| to.tail.run(from.head))(pipe(_, _))))
// e.g. Unit
def runPipe[F[_]: Monad, A: Monoid](pipe: Pipe[F, A, A]): F[A] =
(pipe.head.point[F] |@| pipe.tail.run(mzero[A]).flatMap(runPipe(_)))(_ |+| _)
Cofree
IO, Byte Streams, Etc.
type IOPipe[A, B] = Pipe[Task, A, B]
...
type BytePipe = IOPipe[Array[Byte], Array[Byte]]
Cofree
Merging:Types
type Select[F[_], A] = Coproduct[F, F, A]
type Merge[F[_], A, B] = Pipe[Select[F, ?], A, B]
Cofree
Merging: Function
def merge[F[_]: Applicative, A, B](left: Source[F, A], right: Source[F, A])
(s: Select[Id, Merge[F, A, B]]): Source[F, B] = {
def embed[F[_]: Functor, A](s: Select[F, A]): F[Select[Id, A]] = s.run match {
case -/ (fa) => fa.map(a => Coproduct[Id, Id, A](a.left [A]))
case /-(fa) => fa.map(a => Coproduct[Id, Id, A](a.right[A]))
}
def step(y: Merge[F, A, B], fs: F[Source[F, B]]): Source[F, B] =
Cofree[Kleisli[F, Unit, ?], B](y.head, Kleisli(_ => fs))
s.run match {
case -/ (y) =>
step(y,
(left.tail.run(()) |@| embed(y.tail.run(left.head)))(
(left, y) => merge(left, right)(y)))
case /-(y) =>
step(y,
(right.tail.run(()) |@| embed(y.tail.run(right.head)))(
(right, y) => merge(left, right)(y)))
}
}
Cofree
Forking
def fork[F[_]: Applicative, A](left: Sink[F, A], right: Sink[F, A]): Sink[F, A] =
Cofree[Kleisli[F, A, ?], Unit]((),
Kleisli(a => (left.tail.run(a) |@| right.tail.run(a))(fork(_, _))))
Cofree
Machines
case class Instr[F[_], A](
goLeft: F[A],
goRight: F[A],
goUp: F[A],
goDown: F[A])
// Cofree[Instr[F, ?], A]
def productWith[F[_]: Functor, G[_]: Functor, A, B, C](
c1: Cofree[F, A], c2: Cofree[G, B])(
f: (A, B) => C): Cofree[Product[F, G, ?], C] =
Cofree[Product[F, G, ?], C](f(c1.head, c2.head),
Product((c1.tail.map(productWith(_, c2)(f)),
c2.tail.map(productWith(c1, _)(f)))))
CofreeProduction-Ready?
No, BUT...
ChallengeGo Do SomethingThat'sATinyBit
Simpler...ABitMore Functional...
THANKYOUFollowme onTwitterat@jdegoes

More Related Content

Recently uploaded

chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 

Recently uploaded (20)

chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

STREAMS FOR COINDUCTIVE THINKING

  • 1. Streams for (Co)Free!JohnA. De Goes — @jdegoes
  • 2. Agenda » Induction/Coinduction » Universality of Streams » Cofree: A Principled Stream » Challenge
  • 4. Inductive Programs Examples » Parse a config file » Sort a list » Send an HTTP response » Compute the millionth digit of pi
  • 6. CoinductionStartfroman initialvalueto build up an infinite structure.
  • 7. Coinductive Processes Examples » Produce the next state of the UI given a user- input » Produce current state of config given update to config » Transform stream of requests to responses » Produce (all) the digits of pi
  • 9. ByAnyOther Name Astream isamainstream example ofacoinductive process. » Data processing » Web servers » User-interfaces » Discrete "FRP" » So much more...
  • 10. Streams ✓ Stateful ✓ Incremental computation ✓ Non-termination ✓ Consume & Emit
  • 11. Streams Choices, Choices » Akka Streams » Java Streams » Scalaz-Streams » FS2 » Big Data: Spark, Flink, Pachyderm, Kafka, ad infinitum...
  • 12. John's Laws ofClean FunctionalCode 1.Reasonability is directly proportional to totality & referential-transparency. 2.Composability is inversely proportional to number of data types. 3.Obfuscation is directly proportional to number of lawless interfaces. 4.Correctness is directly proportional to degree of parametric polymorphism. 5.Shoddiness is directly proportional to encapsulation. 6.Volume is inversely proportional to orthogonality.
  • 13. AkkaStream akka.stream AbruptTerminationException AbstractShape ActorAttributes ActorMaterializer ActorMaterializerSettings AmorphousShape Attributes BidiShape BindFailedException BufferOverflowException Client ClosedShape ConnectionException DelayOverflowStrategy EagerClose FanInShape FanInShape10 FanInShape11 FanInShape12 FanInShape13 FanInShape14 FanInShape15 FanInShape16 FanInShape17 FanInShape18 FanInShape19 FanInShape1N FanInShape2 FanInShape20 FanInShape21 FanInShape22 FanInShape3 FanInShape4 FanInShape5 FanInShape6 FanInShape7 FanInShape8 FanInShape9 FanOutShape FanOutShape10 FanOutShape11 FanOutShape12 FanOutShape13 FanOutShape14 FanOutShape15 FanOutShape16 FanOutShape17 FanOutShape18 FanOutShape19 FanOutShape2 FanOutShape20 FanOutShape21 FanOutShape22 FanOutShape3 FanOutShape4 FanOutShape5 FanOutShape6 FanOutShape7 FanOutShape8 FanOutShape9 FlowMonitor FlowMonitorState FlowShape Fusing Graph IgnoreBoth IgnoreCancel IgnoreComplete Inlet InPort IOResult KillSwitch KillSwitches MaterializationContext MaterializationException Materializer MaterializerLoggingProvider Outlet OutPort OverflowStrategy QueueOfferResult RateExceededException Server Shape SharedKillSwitch SinkShape SourceShape StreamLimitReachedException StreamSubscriptionTimeoutSettings StreamSubscriptionTimeoutTerminationMode StreamTcpException SubstreamCancelStrategy Supervision ThrottleMode TLSClientAuth TLSClosing TLSProtocol TLSRole UniformFanInShape UniformFanOutShape UniqueKillSwitch
  • 14. WhatCan Save Us?!? John's Laws ofClean FunctionalCode 1.Reasonability is directly proportional to totality & referential-transparency. 2.Composability is inversely proportional to number of data types. 3.Obfuscation is directly proportional to number of lawless interfaces. 4.Correctness is directly proportional to degree of polymorphism. 5.Shoddiness is directly proportional to encapsulation. 6.Volume is inversely proportional to orthogonality.
  • 15. CofreeALLTHE POWER OFFREE, NOWWITH STREAMING!!!
  • 16. Cofree Huh? // For Functor `F` final case class Cofree[F[_], A](head: A, tail: F[Cofree[F, A]])
  • 17. Cofree:Take 1Cofree[F,A] isacoinductive process thatgenerates A's using effect F.
  • 18. Cofree:Take 2Cofree[F,A] isacurrentposition A ona landscapethatrequires effect Fto movetoanewposition.
  • 19. Cofree Comonad Methods » Where am I? def extract(f: Cofree[F, A]): A » Terraform! def extend(f: Cofree[F, A] => B): Cofree[F, B] » Plus Functor!
  • 20. Cofree Fibs final case class Cofree[F[_], A](head: A, tail: F[Cofree[F, A]]) // final case class Name[A](run: => A) val fibs: Cofree[Name, Int] = { def unfold(prev1: Int, prev2: Int): Cofree[Name, Int] = Cofree(prev1 + prev2, Name(unfold(prev2, prev1 + prev2))) unfold(0, 1) }
  • 21. Cofree Append def append[F[_]: ApplicativePlus, A](c1: Cofree[F, A], c2: Cofree[F, A]): Cofree[F, A] = Cofree(c1.head, c1.tail.map(t => append(t, c2)) <+> c2.point[F])
  • 22. Cofree Collect/Disperse def collect[F[_]: MonadPlus, A](c: Cofree[F, A]): F[Vector[A]] = { val singleton = Vector[A](c.head).point[F] (singleton |@| c.tail.flatMap(collect(_)))(_ ++ _) <+> singleton } def disperse[F[_]: ApplicativePlus, A](seq: Seq[A]): Option[Cofree[F, A]] = seq.foldRight[Option[Cofree[F, A]]](None) { case (a, None) => Some(Cofree(a, mempty[F, Cofree[F, A]])) case (a, Some(tail)) => Some(Cofree(a, tail.point[F])) }
  • 23. Cofree Zip def zipWith[F[_]: Zip: Functor, A, B, C]( c1: Cofree[F, A], c2: Cofree[F, B])( f: (A, B) => C): Cofree[F, C] = Cofree( f(c1.head, c2.head), Zip[F].zipWith(c1.tail, c2.tail)(zipWith(_, _)(f)))
  • 24. Cofree Scan def scan[F[_]: Functor, A, S]( c: Cofree[F, A])(s: S)(f: (S, A) => S): Cofree[F, S] = { val s2 = f(s, c.head) Cofree(s2, c.tail.map(scan(_)(s2)(f))) }
  • 25. Cofree Filter def zeros[F[_]: Functor, A: Monoid](c: Cofree[F, A])(p: A => Boolean): Cofree[F, A] = if (p(c.head)) Cofree(c.head, c.tail.map(zeros(_)(p))) else Cofree(mzero[A], c.tail.map(zeros(_)(p))) def filter[F[_]: Monad, A](c: Cofree[F, A])(p: A => Boolean): F[Cofree[F, A]] = if (p(c.head)) Cofree(c.head, c.tail.flatMap(filter(_)(p))).point[F] else c.tail.flatMap(filter(_)(p))
  • 26. Cofree Pipes:Types // final case class Kleisli[F[_], A, B](run: A => F[B]) type Pipe[F[_], A, B] = Cofree[Kleisli[F, A, ?], B] type Source[F[_], A] = Pipe[F, Unit, A] type Sink[F[_], A] = Pipe[F, A, Unit]
  • 27. Cofree Pipes: Utilities def pipe[F[_]: Applicative, A, B, C](from: Pipe[F, A, B], to: Pipe[F, B, C]): Pipe[F, A, C] = Cofree[Kleisli[F, A, ?], C]( to.head, Kleisli(a => (from.tail.run(a) |@| to.tail.run(from.head))(pipe(_, _)))) // e.g. Unit def runPipe[F[_]: Monad, A: Monoid](pipe: Pipe[F, A, A]): F[A] = (pipe.head.point[F] |@| pipe.tail.run(mzero[A]).flatMap(runPipe(_)))(_ |+| _)
  • 28. Cofree IO, Byte Streams, Etc. type IOPipe[A, B] = Pipe[Task, A, B] ... type BytePipe = IOPipe[Array[Byte], Array[Byte]]
  • 29. Cofree Merging:Types type Select[F[_], A] = Coproduct[F, F, A] type Merge[F[_], A, B] = Pipe[Select[F, ?], A, B]
  • 30. Cofree Merging: Function def merge[F[_]: Applicative, A, B](left: Source[F, A], right: Source[F, A]) (s: Select[Id, Merge[F, A, B]]): Source[F, B] = { def embed[F[_]: Functor, A](s: Select[F, A]): F[Select[Id, A]] = s.run match { case -/ (fa) => fa.map(a => Coproduct[Id, Id, A](a.left [A])) case /-(fa) => fa.map(a => Coproduct[Id, Id, A](a.right[A])) } def step(y: Merge[F, A, B], fs: F[Source[F, B]]): Source[F, B] = Cofree[Kleisli[F, Unit, ?], B](y.head, Kleisli(_ => fs)) s.run match { case -/ (y) => step(y, (left.tail.run(()) |@| embed(y.tail.run(left.head)))( (left, y) => merge(left, right)(y))) case /-(y) => step(y, (right.tail.run(()) |@| embed(y.tail.run(right.head)))( (right, y) => merge(left, right)(y))) } }
  • 31. Cofree Forking def fork[F[_]: Applicative, A](left: Sink[F, A], right: Sink[F, A]): Sink[F, A] = Cofree[Kleisli[F, A, ?], Unit]((), Kleisli(a => (left.tail.run(a) |@| right.tail.run(a))(fork(_, _))))
  • 32. Cofree Machines case class Instr[F[_], A]( goLeft: F[A], goRight: F[A], goUp: F[A], goDown: F[A]) // Cofree[Instr[F, ?], A] def productWith[F[_]: Functor, G[_]: Functor, A, B, C]( c1: Cofree[F, A], c2: Cofree[G, B])( f: (A, B) => C): Cofree[Product[F, G, ?], C] = Cofree[Product[F, G, ?], C](f(c1.head, c2.head), Product((c1.tail.map(productWith(_, c2)(f)), c2.tail.map(productWith(c1, _)(f)))))