Traversals for all ocasions

TRAVERSALS FOR ALL
OCCASIONS
Luka Jacobowitz
Software Developer at codecentric
Co-organizer of ScalaDus and
IdrisDus
Maintainer of cats, cats-effect,
cats-mtl, OutWatch
Enthusiastic about FP
About me
Motivation
● Traversable is my favorite type class
● Not enough people know about it
● Even less people know about some of the less common traversals out there
● Have some fun while learning!
Motivation
Teaser
How do you create a List of Http Requests run them all in parallel and if errors
occur accumulate them?
userIdList.parTraverse(request).value
Traverse
[T[_]: Traverse, F[_]: Applicative, A]: T[F[A]] => F[T[A]]
E.g.
List[Future[A]] => Future[List[A]]
Vector[Option[A]] => Option[Vector[A]]
Traverse
[T[_]: Traverse, F[_]: Applicative, A]: T[F[A]] => F[T[A]]
Traverse runs an action(F[_]) for every element in a data structure (T[_]), and
accumulates the results.
Traverse
trait Applicative[F[_]] {
def map2[A, B, C](fa: F[A], fb: F[B])(f: (A, B) => C): F[C]
def pure[A](a: A): F[A]
}
Applicatives allow us to combine two or more independent values inside a
context.
Traverse
trait Traverse[T[_]] {
def sequence[F[_]: Applicative, A](tfa: T[F[A]]): F[T[A]]
def traverse[F[_]: Applicative, A, B](ta: T[A], f: A => F[B]): F[T[B]]
}
t.traverse(f) <-> t.map(f).sequence
Traverse
List[Future[A]] => Future[List[A]]
Vector[Option[A]] => Option[Vector[A]]
Either[E, IO[A]] => IO[Either[E, A]]
type EitherE[A] = Either[E, A]
List[Validated[E, A]] => Validated[E, List[A]]
FoldMap
trait Foldable[T[_]] {
def foldMap[A, M: Monoid](ta: T[A], f: A => M): M
def fold[M: Monoid](ta: T[M]): M
}
t.foldMap(f) <-> t.map(f).fold
def foldMap[A, M: Monoid](ta: T[A], f: A => M): M =
ta.traverse(a => Const(f(a))).getConst
NonEmpty
trait Reducible[T[_]] {
def reduceMap[A, S: Semigroup](ta: T[A], f: A => S): S
def reduce[S: Semigroup](ta: T[S]): S
}
trait NonEmptyTraverse[T[_]] {
def nonEmptyTraverse[F[_]: Apply](ta: T[A], f: A => F[B]): F[T[B]]
def nonEmptySequence[F[_]: Apply](ta: T[F[A]]): F[T[A]]
}
t.reduceMap(f) <-> t.map(f).reduce
t.nonEmptyTraverse(f) <-> t.map(f).nonEmptySequence
NonEmpty
def maximum[A: Order](nel: NonEmptyList[A]): A =
reduceMap(nel)(Max)
def minimum[A: Order](nel: NonEmptyList[A]): A =
reduceMap(nel)(Min)
NonEmpty
def countWords(text: String): Map[String, Int] =
words.split(" ").groupBy(identity).mapValues(_.length)
val lines: NonEmptyList[String]
val result: Map[String, NonEmptyList[Int]] =
lines.nonEmptyTraverse(countWords)
Commutativity
trait UnorderedFoldable[T[_]] {
def unorderedFold[M: CommutativeMonoid](ta: T[M]): M
}
trait UnorderedTraverse[T[_]] {
def unorderedSequence[F[_]: CommutativeApplicative, A]
(ta: T[F[A]]): F[T[A]]
}
Commutativity
CommutativeMonoid:
a |+| b <-> b |+| a
E.g: Int, Set[String]
Commutativity
val users: HashSet[User]
val result =
users.unorderedFoldMap(_.billableHours)
Commutativity
CommutativeApplicative:
map2(fa, fb)((a, b) => f(a, b)) <-> map2(fb, fa)((b, a) => f(a, b))
fa *> fb <-> fb <* fa
E.g. Option, ValidatedNes
Commutativity
type ValidatedNes[E, A] = Validated[NonEmptySet[E], A]
val result: ValidatedNes[Error, RDD[User]] =
users.unorderedTraverse(validate)
FlatTraverse
trait Traverse[T[_]] {
def flatTraverse[G[_]: Applicative, A, B](ta: T[A])
(f: A => G[T[B]])(implicit T: FlatMap[T]): G[T[B]]
}
ta.traverse(f).map(_.flatten) <-> ta.flatTraverse(f)
FlatTraverse
val maybeUser: Option[User]
def fetchAddress(user: User): IO[Option[Address]]
val result: IO[Option[Address]] =
maybeUser.flatTraverse(fetchAddress)
Parallelism
trait Parallel[M[_]: Monad, F[_]: Applicative] {
def parallel: FunctionK[M, F]
def sequential: FunctionK[F, M]
}
def parSequence[T[_], M[_], F[_], A](ta: T[M[A]])
(implicit P: Parallel[M, F], T: Traverse[T]): M[T[A]]
Revisiting the teaser
def request(userId: Int): EitherT[IO, Nel[Error], User]
val result: IO[EitherNel[Error, List[User]]] =
userIdList.parTraverse(request).value
EitherT[IO, E, A] ⇔ Nested[ParIO, Validated[E, ?], A]
IO[Either[E, A]] ⇔ ParIO[Validated[E, A]]
Other traversals
traverseWithIndex
unorderedFlatTraverse
traverseWithIndexM
traverse_
parFlatTraverse
nonEmptyFlatTraverse
parNonEmptyFlatTraverse
parNonEmptyUnorderedTraverse
Other traversals
traverseWithIndex
unorderedFlatTraverse
traverseWithIndexM
traverse_
parFlatTraverse
nonEmptyFlatTraverse
parNonEmptyFlatTraverse
parNonEmptyUnorderedTraverse
+ Sequence versions
+ Almost every other
conceivable
combination
Useful stuff!
def parNonEmptyUnorderedSequence
[T[_]: NonEmptyUnorderedTraverse, M[_], F[_], A](ta: T[M[A]])
(implicit P: NonEmptyCommutativeParallel[M, F]): M[T[A]]
What could possibly be an instance for this???
NonEmptyUnorderedTraverse: NonEmptyRDD, NonEmptyHashMap
NonEmptyCommutativeParallel: NonEmptyList ⇔ NonEmptyZipList
Useful stuff!
def groupByNem[A, K](nel: NonEmptyList[A])
(f: A => K): NonEmptyHashMap[K, NonEmptyList[A]]
users.groupByNem(_.address)
.parNonEmptyUnorderedSequence
Summary
Traverse is a great abstraction, because it allows us to traverse data structures
using Applicative Functors, which represent independent computations.
These traversals capture the essence of imperative loops over these data
structures.
We can add or remove constraints to the action(F[_]) or the structure types(T[_])
to get slightly different traversals.
Thank you all for
listening!
Twitter:
@LukaJacobowitz
GitHub:
LukaJCB
1 of 29

Recommended

Monoids, monoids, monoids by
Monoids, monoids, monoidsMonoids, monoids, monoids
Monoids, monoids, monoidsLuka Jacobowitz
1.1K views57 slides
Monoids, Monoids, Monoids - ScalaLove 2020 by
Monoids, Monoids, Monoids - ScalaLove 2020Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020Luka Jacobowitz
739 views58 slides
Testing in the World of Functional Programming by
Testing in the World of Functional ProgrammingTesting in the World of Functional Programming
Testing in the World of Functional ProgrammingLuka Jacobowitz
1.6K views37 slides
Oh, All the things you'll traverse by
Oh, All the things you'll traverseOh, All the things you'll traverse
Oh, All the things you'll traverseLuka Jacobowitz
1K views46 slides
Principled Error Handling with FP by
Principled Error Handling with FPPrincipled Error Handling with FP
Principled Error Handling with FPLuka Jacobowitz
2.4K views37 slides
Scala Functional Patterns by
Scala Functional PatternsScala Functional Patterns
Scala Functional Patternsleague
1.4K views33 slides

More Related Content

What's hot

Fp in scala with adts part 2 by
Fp in scala with adts part 2Fp in scala with adts part 2
Fp in scala with adts part 2Hang Zhao
1K views26 slides
First-Class Patterns by
First-Class PatternsFirst-Class Patterns
First-Class PatternsJohn De Goes
3.3K views30 slides
Scala. Introduction to FP. Monads by
Scala. Introduction to FP. MonadsScala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsKirill Kozlov
1.1K views61 slides
Fp in scala part 1 by
Fp in scala part 1Fp in scala part 1
Fp in scala part 1Hang Zhao
961 views27 slides
Python programming : Standard Input and Output by
Python programming : Standard Input and OutputPython programming : Standard Input and Output
Python programming : Standard Input and OutputEmertxe Information Technologies Pvt Ltd
5.4K views16 slides
Map, Reduce and Filter in Swift by
Map, Reduce and Filter in SwiftMap, Reduce and Filter in Swift
Map, Reduce and Filter in SwiftAleksandras Smirnovas
3.4K views34 slides

What's hot(19)

Fp in scala with adts part 2 by Hang Zhao
Fp in scala with adts part 2Fp in scala with adts part 2
Fp in scala with adts part 2
Hang Zhao1K views
First-Class Patterns by John De Goes
First-Class PatternsFirst-Class Patterns
First-Class Patterns
John De Goes3.3K views
Scala. Introduction to FP. Monads by Kirill Kozlov
Scala. Introduction to FP. MonadsScala. Introduction to FP. Monads
Scala. Introduction to FP. Monads
Kirill Kozlov1.1K views
Fp in scala part 1 by Hang Zhao
Fp in scala part 1Fp in scala part 1
Fp in scala part 1
Hang Zhao961 views
7 Habits For a More Functional Swift by Jason Larsen
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional Swift
Jason Larsen12.1K views
Introduction to Monads in Scala (1) by stasimus
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
stasimus10.2K views
The Essence of the Iterator Pattern by Eric Torreborre
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator Pattern
Eric Torreborre1.5K views
Refactoring Functional Type Classes by John De Goes
Refactoring Functional Type ClassesRefactoring Functional Type Classes
Refactoring Functional Type Classes
John De Goes6.9K views
Atomically { Delete Your Actors } by John De Goes
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }
John De Goes2.1K views
Algebraic Data Types and Origami Patterns by Vasil Remeniuk
Algebraic Data Types and Origami PatternsAlgebraic Data Types and Origami Patterns
Algebraic Data Types and Origami Patterns
Vasil Remeniuk1.7K views
Blazing Fast, Pure Effects without Monads — LambdaConf 2018 by John De Goes
Blazing Fast, Pure Effects without Monads — LambdaConf 2018Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
John De Goes4.6K views
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics by John De Goes
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
John De Goes7.2K views
The Next Great Functional Programming Language by John De Goes
The Next Great Functional Programming LanguageThe Next Great Functional Programming Language
The Next Great Functional Programming Language
John De Goes4.2K views
The Essence of the Iterator Pattern (pdf) by Eric Torreborre
The Essence of the Iterator Pattern (pdf)The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)
Eric Torreborre557 views
N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and... by Philip Schwarz
N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...
Philip Schwarz842 views

Similar to Traversals for all ocasions

Trafaret: monads and python by
Trafaret: monads and pythonTrafaret: monads and python
Trafaret: monads and pythonMikhail Krivushin
675 views32 slides
Functions, Types, Programs and Effects by
Functions, Types, Programs and EffectsFunctions, Types, Programs and Effects
Functions, Types, Programs and EffectsRaymond Roestenburg
368 views81 slides
Practical scalaz by
Practical scalazPractical scalaz
Practical scalazoxbow_lakes
4.6K views41 slides
Power of functions in a typed world by
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed worldDebasish Ghosh
909 views88 slides
Types by Adform Research by
Types by Adform ResearchTypes by Adform Research
Types by Adform ResearchVasil Remeniuk
635 views29 slides
Typeclasses by
TypeclassesTypeclasses
Typeclassesekalyoncu
696 views44 slides

Similar to Traversals for all ocasions(20)

Practical scalaz by oxbow_lakes
Practical scalazPractical scalaz
Practical scalaz
oxbow_lakes4.6K views
Power of functions in a typed world by Debasish Ghosh
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed world
Debasish Ghosh909 views
Typeclasses by ekalyoncu
TypeclassesTypeclasses
Typeclasses
ekalyoncu696 views
Functional programming with_scala by Raymond Tay
Functional programming with_scalaFunctional programming with_scala
Functional programming with_scala
Raymond Tay2.1K views
Peeking inside the engine of ZIO SQL.pdf by JaroslavRegec1
Peeking inside the engine of ZIO SQL.pdfPeeking inside the engine of ZIO SQL.pdf
Peeking inside the engine of ZIO SQL.pdf
JaroslavRegec1153 views
Types Working for You, Not Against You by C4Media
Types Working for You, Not Against YouTypes Working for You, Not Against You
Types Working for You, Not Against You
C4Media277 views
Beginning Scala Svcc 2009 by David Pollak
Beginning Scala Svcc 2009Beginning Scala Svcc 2009
Beginning Scala Svcc 2009
David Pollak855 views
Generic Functional Programming with Type Classes by Tapio Rautonen
Generic Functional Programming with Type ClassesGeneric Functional Programming with Type Classes
Generic Functional Programming with Type Classes
Tapio Rautonen290 views
Morel, a Functional Query Language by Julian Hyde
Morel, a Functional Query LanguageMorel, a Functional Query Language
Morel, a Functional Query Language
Julian Hyde1.1K views
Monads - Dublin Scala meetup by Mikhail Girkin
Monads - Dublin Scala meetupMonads - Dublin Scala meetup
Monads - Dublin Scala meetup
Mikhail Girkin764 views
Tip Top Typing - A Look at Python Typing by Patrick Viafore
Tip Top Typing - A Look at Python TypingTip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python Typing
Patrick Viafore227 views
Ejercicios de estilo en la programación by Software Guru
Ejercicios de estilo en la programaciónEjercicios de estilo en la programación
Ejercicios de estilo en la programación
Software Guru725 views
Intro to Functional Programming with Scala - #psuweb by DerekMorr
Intro to Functional Programming with Scala - #psuwebIntro to Functional Programming with Scala - #psuweb
Intro to Functional Programming with Scala - #psuweb
DerekMorr624 views

More from Luka Jacobowitz

Up and Running with the Typelevel Stack by
Up and Running with the Typelevel StackUp and Running with the Typelevel Stack
Up and Running with the Typelevel StackLuka Jacobowitz
394 views15 slides
Principled Error Handling - Scalapeño by
Principled Error Handling - ScalapeñoPrincipled Error Handling - Scalapeño
Principled Error Handling - ScalapeñoLuka Jacobowitz
237 views39 slides
Advanced Tagless Final - Saying Farewell to Free by
Advanced Tagless Final - Saying Farewell to FreeAdvanced Tagless Final - Saying Farewell to Free
Advanced Tagless Final - Saying Farewell to FreeLuka Jacobowitz
2K views30 slides
Building a Tagless Final DSL for WebGL by
Building a Tagless Final DSL for WebGLBuilding a Tagless Final DSL for WebGL
Building a Tagless Final DSL for WebGLLuka Jacobowitz
2.1K views17 slides
What Referential Transparency can do for you by
What Referential Transparency can do for youWhat Referential Transparency can do for you
What Referential Transparency can do for youLuka Jacobowitz
730 views29 slides
Scala UA 2017 by
Scala UA 2017Scala UA 2017
Scala UA 2017Luka Jacobowitz
137 views16 slides

More from Luka Jacobowitz(8)

Up and Running with the Typelevel Stack by Luka Jacobowitz
Up and Running with the Typelevel StackUp and Running with the Typelevel Stack
Up and Running with the Typelevel Stack
Luka Jacobowitz394 views
Principled Error Handling - Scalapeño by Luka Jacobowitz
Principled Error Handling - ScalapeñoPrincipled Error Handling - Scalapeño
Principled Error Handling - Scalapeño
Luka Jacobowitz237 views
Advanced Tagless Final - Saying Farewell to Free by Luka Jacobowitz
Advanced Tagless Final - Saying Farewell to FreeAdvanced Tagless Final - Saying Farewell to Free
Advanced Tagless Final - Saying Farewell to Free
Luka Jacobowitz2K views
Building a Tagless Final DSL for WebGL by Luka Jacobowitz
Building a Tagless Final DSL for WebGLBuilding a Tagless Final DSL for WebGL
Building a Tagless Final DSL for WebGL
Luka Jacobowitz2.1K views
What Referential Transparency can do for you by Luka Jacobowitz
What Referential Transparency can do for youWhat Referential Transparency can do for you
What Referential Transparency can do for you
Luka Jacobowitz730 views
Reactive Programming in the Browser feat. Scala.js and Rx by Luka Jacobowitz
Reactive Programming in the Browser feat. Scala.js and RxReactive Programming in the Browser feat. Scala.js and Rx
Reactive Programming in the Browser feat. Scala.js and Rx
Luka Jacobowitz629 views
Reactive Programming in the Browser feat. Scala.js and PureScript by Luka Jacobowitz
Reactive Programming in the Browser feat. Scala.js and PureScriptReactive Programming in the Browser feat. Scala.js and PureScript
Reactive Programming in the Browser feat. Scala.js and PureScript
Luka Jacobowitz846 views

Recently uploaded

360 graden fabriek by
360 graden fabriek360 graden fabriek
360 graden fabriekinfo33492
165 views25 slides
Playwright Retries by
Playwright RetriesPlaywright Retries
Playwright Retriesartembondar5
6 views1 slide
Dapr Unleashed: Accelerating Microservice Development by
Dapr Unleashed: Accelerating Microservice DevelopmentDapr Unleashed: Accelerating Microservice Development
Dapr Unleashed: Accelerating Microservice DevelopmentMiroslav Janeski
15 views29 slides
How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile... by
How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...
How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...Stefan Wolpers
42 views38 slides
Ports-and-Adapters Architecture for Embedded HMI by
Ports-and-Adapters Architecture for Embedded HMIPorts-and-Adapters Architecture for Embedded HMI
Ports-and-Adapters Architecture for Embedded HMIBurkhard Stubert
33 views19 slides
Flask-Python.pptx by
Flask-Python.pptxFlask-Python.pptx
Flask-Python.pptxTriloki Gupta
9 views12 slides

Recently uploaded(20)

360 graden fabriek by info33492
360 graden fabriek360 graden fabriek
360 graden fabriek
info33492165 views
Dapr Unleashed: Accelerating Microservice Development by Miroslav Janeski
Dapr Unleashed: Accelerating Microservice DevelopmentDapr Unleashed: Accelerating Microservice Development
Dapr Unleashed: Accelerating Microservice Development
Miroslav Janeski15 views
How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile... by Stefan Wolpers
How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...
How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...
Stefan Wolpers42 views
Ports-and-Adapters Architecture for Embedded HMI by Burkhard Stubert
Ports-and-Adapters Architecture for Embedded HMIPorts-and-Adapters Architecture for Embedded HMI
Ports-and-Adapters Architecture for Embedded HMI
Burkhard Stubert33 views
predicting-m3-devopsconMunich-2023-v2.pptx by Tier1 app
predicting-m3-devopsconMunich-2023-v2.pptxpredicting-m3-devopsconMunich-2023-v2.pptx
predicting-m3-devopsconMunich-2023-v2.pptx
Tier1 app12 views
FOSSLight Community Day 2023-11-30 by Shane Coughlan
FOSSLight Community Day 2023-11-30FOSSLight Community Day 2023-11-30
FOSSLight Community Day 2023-11-30
Shane Coughlan7 views
aATP - New Correlation Confirmation Feature.pptx by EsatEsenek1
aATP - New Correlation Confirmation Feature.pptxaATP - New Correlation Confirmation Feature.pptx
aATP - New Correlation Confirmation Feature.pptx
EsatEsenek1205 views
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated... by TomHalpin9
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...
TomHalpin96 views
JioEngage_Presentation.pptx by admin125455
JioEngage_Presentation.pptxJioEngage_Presentation.pptx
JioEngage_Presentation.pptx
admin1254558 views
Bootstrapping vs Venture Capital.pptx by Zeljko Svedic
Bootstrapping vs Venture Capital.pptxBootstrapping vs Venture Capital.pptx
Bootstrapping vs Venture Capital.pptx
Zeljko Svedic15 views
How Workforce Management Software Empowers SMEs | TraQSuite by TraQSuite
How Workforce Management Software Empowers SMEs | TraQSuiteHow Workforce Management Software Empowers SMEs | TraQSuite
How Workforce Management Software Empowers SMEs | TraQSuite
TraQSuite6 views
Generic or specific? Making sensible software design decisions by Bert Jan Schrijver
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
DRYiCE™ iAutomate: AI-enhanced Intelligent Runbook Automation by HCLSoftware
DRYiCE™ iAutomate: AI-enhanced Intelligent Runbook AutomationDRYiCE™ iAutomate: AI-enhanced Intelligent Runbook Automation
DRYiCE™ iAutomate: AI-enhanced Intelligent Runbook Automation
HCLSoftware6 views
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium... by Lisi Hocke
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...
Lisi Hocke35 views

Traversals for all ocasions