SlideShare a Scribd company logo
1 of 21
MTL IN 15 MINUTES
Pere Villega (@pvillega)
MTL IN 15 MINUTES - @PVILLEGA
• 2016 - Free Monad
• 2017 - Recursion Schemes
• 2018 - MTL
• 2019 - ???
MTL IN 15 MINUTES - @PVILLEGA
• Pawel Szulc - A road trip with Monads:
https://www.youtube.com/watch?v=y_QHSDOV
• John De Goes - FP to the Max
https://www.youtube.com/watch?v=sxudIMiOo6
• Http4s error handling with Cats Meow MTL
https://typelevel.org/blog/2018/08/25/http4s-erro
MTL IN 15 MINUTES - @PVILLEGA
INTERPRETERS?
TAGLESS FINAL?
MTL IN 15 MINUTES - @PVILLEGA
final case class Topic(id: Int, title: String)
trait TopicServiceAlg[F[_]] {
def createTopic(id: Int,
title: String): F[Unit]
def getById(id: Int): F[Option[Topic]]
def delete(id: Int): F[Option[Topic]]
}
def aMethod[F[_]](
topicService: TopicServiceAlg[F]): F[Topic]
MTL IN 15 MINUTES - @PVILLEGA
class TestTopic extends TopicServiceAlg[Id] {
// mutability, don't look!
private val map =
mutable.Map.empty[Int, Topic]
def createTopic(id: Int,
title: String): Id[Unit] =
map += id → Topic(id, title)
def getById(id: Int): Id[Option[Topic]] =
map.get(id)
def delete(id: Int): Id[Option[Topic]] =
map.remove(id)
}
MTL IN 15 MINUTES - @PVILLEGA
class ExternalTopicService extends TopicServiceAlg[IO] {
def createTopic(id: Int,
title: String): IO[Unit]
def getById(id: Int): IO[Option[Topic]]
def delete(id: Int): IO[Option[Topic]]
}
MTL IN 15 MINUTES - @PVILLEGA
type ErrorF[A]= EitherT[IO, Error, A]
type LogF[A] = WriterT[ErrorF, Chain[String], A]
type ConfigF[A] = ReaderT[LogF, Config, A]
type OurF[A] = ConfigF[A]
MTL IN 15 MINUTES - @PVILLEGA
def forOfDeath[A]: OurF[A] =
for {
out ← ReaderT[LogF, Config, A](
(config: Config) ⇒
WriterT[ErrorF, Chain[String], A] {
EitherT[IO, Error, A] {
???
}
}
)
} yield out
MTL IN 15 MINUTES - @PVILLEGA
MTL IN 15 MINUTES - @PVILLEGA
MTL IN 15 MINUTES - @PVILLEGA
ApplicativeAsk[F, E] Configuration passing ReaderT
FunctorRaise[F, E]
Raise errors and
shortcircuit
EitherT
FunctorTell[F, L] Log values WriterT
MonadState[F, S] Manage state StateT
MTL IN 15 MINUTES - @PVILLEGA
def someMethod[F[_]](implicit
ev: FunctorRaise[F, Error]
): F[Nothing] =
ev.raise(ErrorSubtype("boo!"))
MTL IN 15 MINUTES - @PVILLEGA
implicit def reader[F[_]: Applicative]: ApplicativeAsk[F, Config] =
new DefaultApplicativeAsk[F, Config] {
override val applicative: Applicative[F]=
Applicative[F]
override def ask: F[Config]=
applicative.pure(Config("url"))
}
MTL IN 15 MINUTES - @PVILLEGA
implicit def writer[F[_]: Applicative]: FunctorTell[F, Chain[String]] =
new DefaultFunctorTell[F, Chain[String]] {
override val functor: Functor[F]=
Functor[F]
def tell(l: Chain[String]): F[Unit] =
println(l.show).pure[F]
}
MTL IN 15 MINUTES - @PVILLEGA
type OurF[A] = EitherT[IO, Error, A]
def ok[F[_]: Monad](alg: TopicServiceAlg[F])(implicit
Err: FunctorRaise[F, Error],
Cfg: ApplicativeAsk[F, Config],
Log: FunctorTell[F, Chain[String]]
): F[Topic] =
for {
server ← Cfg.reader(_.server)
_ ← Log.tell(Chain.one(s"In $server"))
tpc ← alg.getById(10)
res ← tpc
.fold(Err.raise(missingTopic))
(Monad[F].pure)
} yield res
MTL IN 15 MINUTES - @PVILLEGA
MTL IN 15 MINUTES - @PVILLEGA
type Headers = Map[String, String]
case class User(name: String)
case class Request(h: Headers, u: User)
def greetUser[F[_]: Functor](implicit F: MonadState[F, User]): F[String
def addRequestHeader[F[_]: Sync](implicit F: MonadState[F, Header
def handleGreetRequest[F[_]: Sync](implicit F: MonadState[F, Reque
for {
_ <- addRequestHeader[F]
r <- greetUser[F]
} yield r
MTL IN 15 MINUTES - @PVILLEGA
def getAndIncrement[F[_]: Apply](implicit
MS: MonadState[F, Int]) =
MS.get <* MS.modify(_ + 1)
for {
ref <- Ref.of[IO](0)
out <- ref.runState { implicit ms =>
getAndIncrement[IO].replicateA(3).as("Done")
}
state <- ref.get
} yield (out, state) == ("Done", 3)
MTL IN 15 MINUTES - @PVILLEGA
+ Finally Tagless
+ Performance
- Transformer Complexity
– Questions please :)
“If you work at UK’s home office or know
someone there, please talk to me after the
Q&A.”

More Related Content

Recently uploaded

Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
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
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
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
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina 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.
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
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
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?Watsoo Telematics
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
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
 

Recently uploaded (20)

Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
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
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
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)
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
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 ...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
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
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
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
 

Featured

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
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...DevGAMM Conference
 
Barbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationBarbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationErica Santiago
 

Featured (20)

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...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 
More than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike RoutesMore than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike Routes
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
 
Barbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationBarbie - Brand Strategy Presentation
Barbie - Brand Strategy Presentation
 

Mtl in 15m

  • 1. MTL IN 15 MINUTES Pere Villega (@pvillega)
  • 2. MTL IN 15 MINUTES - @PVILLEGA • 2016 - Free Monad • 2017 - Recursion Schemes • 2018 - MTL • 2019 - ???
  • 3. MTL IN 15 MINUTES - @PVILLEGA • Pawel Szulc - A road trip with Monads: https://www.youtube.com/watch?v=y_QHSDOV • John De Goes - FP to the Max https://www.youtube.com/watch?v=sxudIMiOo6 • Http4s error handling with Cats Meow MTL https://typelevel.org/blog/2018/08/25/http4s-erro
  • 4. MTL IN 15 MINUTES - @PVILLEGA INTERPRETERS? TAGLESS FINAL?
  • 5. MTL IN 15 MINUTES - @PVILLEGA final case class Topic(id: Int, title: String) trait TopicServiceAlg[F[_]] { def createTopic(id: Int, title: String): F[Unit] def getById(id: Int): F[Option[Topic]] def delete(id: Int): F[Option[Topic]] } def aMethod[F[_]]( topicService: TopicServiceAlg[F]): F[Topic]
  • 6. MTL IN 15 MINUTES - @PVILLEGA class TestTopic extends TopicServiceAlg[Id] { // mutability, don't look! private val map = mutable.Map.empty[Int, Topic] def createTopic(id: Int, title: String): Id[Unit] = map += id → Topic(id, title) def getById(id: Int): Id[Option[Topic]] = map.get(id) def delete(id: Int): Id[Option[Topic]] = map.remove(id) }
  • 7. MTL IN 15 MINUTES - @PVILLEGA class ExternalTopicService extends TopicServiceAlg[IO] { def createTopic(id: Int, title: String): IO[Unit] def getById(id: Int): IO[Option[Topic]] def delete(id: Int): IO[Option[Topic]] }
  • 8. MTL IN 15 MINUTES - @PVILLEGA type ErrorF[A]= EitherT[IO, Error, A] type LogF[A] = WriterT[ErrorF, Chain[String], A] type ConfigF[A] = ReaderT[LogF, Config, A] type OurF[A] = ConfigF[A]
  • 9. MTL IN 15 MINUTES - @PVILLEGA def forOfDeath[A]: OurF[A] = for { out ← ReaderT[LogF, Config, A]( (config: Config) ⇒ WriterT[ErrorF, Chain[String], A] { EitherT[IO, Error, A] { ??? } } ) } yield out
  • 10. MTL IN 15 MINUTES - @PVILLEGA
  • 11. MTL IN 15 MINUTES - @PVILLEGA
  • 12. MTL IN 15 MINUTES - @PVILLEGA ApplicativeAsk[F, E] Configuration passing ReaderT FunctorRaise[F, E] Raise errors and shortcircuit EitherT FunctorTell[F, L] Log values WriterT MonadState[F, S] Manage state StateT
  • 13. MTL IN 15 MINUTES - @PVILLEGA def someMethod[F[_]](implicit ev: FunctorRaise[F, Error] ): F[Nothing] = ev.raise(ErrorSubtype("boo!"))
  • 14. MTL IN 15 MINUTES - @PVILLEGA implicit def reader[F[_]: Applicative]: ApplicativeAsk[F, Config] = new DefaultApplicativeAsk[F, Config] { override val applicative: Applicative[F]= Applicative[F] override def ask: F[Config]= applicative.pure(Config("url")) }
  • 15. MTL IN 15 MINUTES - @PVILLEGA implicit def writer[F[_]: Applicative]: FunctorTell[F, Chain[String]] = new DefaultFunctorTell[F, Chain[String]] { override val functor: Functor[F]= Functor[F] def tell(l: Chain[String]): F[Unit] = println(l.show).pure[F] }
  • 16. MTL IN 15 MINUTES - @PVILLEGA type OurF[A] = EitherT[IO, Error, A] def ok[F[_]: Monad](alg: TopicServiceAlg[F])(implicit Err: FunctorRaise[F, Error], Cfg: ApplicativeAsk[F, Config], Log: FunctorTell[F, Chain[String]] ): F[Topic] = for { server ← Cfg.reader(_.server) _ ← Log.tell(Chain.one(s"In $server")) tpc ← alg.getById(10) res ← tpc .fold(Err.raise(missingTopic)) (Monad[F].pure) } yield res
  • 17. MTL IN 15 MINUTES - @PVILLEGA
  • 18. MTL IN 15 MINUTES - @PVILLEGA type Headers = Map[String, String] case class User(name: String) case class Request(h: Headers, u: User) def greetUser[F[_]: Functor](implicit F: MonadState[F, User]): F[String def addRequestHeader[F[_]: Sync](implicit F: MonadState[F, Header def handleGreetRequest[F[_]: Sync](implicit F: MonadState[F, Reque for { _ <- addRequestHeader[F] r <- greetUser[F] } yield r
  • 19. MTL IN 15 MINUTES - @PVILLEGA def getAndIncrement[F[_]: Apply](implicit MS: MonadState[F, Int]) = MS.get <* MS.modify(_ + 1) for { ref <- Ref.of[IO](0) out <- ref.runState { implicit ms => getAndIncrement[IO].replicateA(3).as("Done") } state <- ref.get } yield (out, state) == ("Done", 3)
  • 20. MTL IN 15 MINUTES - @PVILLEGA + Finally Tagless + Performance - Transformer Complexity
  • 21. – Questions please :) “If you work at UK’s home office or know someone there, please talk to me after the Q&A.”

Editor's Notes

  1. Hi, welcome everyone. I’m Pere Villega, Scala contractor, and today I’m going to talk about MTL
  2. Scala community seems to go over an annual cycle in which they choose a technique and spam it across conferences all year long. It happened with Free, Recursion schemes, and now with MTL. So we are going to talk about MTL, so we all understand what it is, and then we can forget about it next year :)
  3. I need to start with some disclaimers. I recommend you to watch and read these presentations I link on the slide. This is a 15m talk, and MTL is something you can talk about for much longer. I will leave many things on the side, simplify others, and even make some mistakes. The aim of this talk is just to give you a small introduction on why does it exist and why is it useful, so then you can decide if you are interested on learning more about it.
  4. Question for the audience: who knows about interpreters? And about tagless final? There was a talk by Dave Gurnell today that you should watch if you have not seen it, as it gives solid foundations for what we are going to discuss now.
  5. From now on in the talk when I say tagless final please understand parameterized interfaces and interpreters. Let’s do a quick recap. This is a technique to separate our business domain from our implementation. Here we define an interface for our topic service, as a trait, without implementation, parameterised with an effect F. Something that we can use in our business logic, as we can see in this method. Note we are going to keep the code simple, so we focus on the relevant concepts
  6. The advantage of doing that is that we can have multiple implementations of that trait that we can swap as needed. Ex java programmers will remember the rule of coding against the interface. We can have this test implementation backed up by a map. This removes the need of mocking frameworks.
  7. Or our production implementation relying on an external service which uses IO to isolate the side effects. We can use anything as F, including our own custom made F.
  8. This defining our own F is where the problem starts. We want our F, our effect, to have some properties: error handling as we don’t throw exceptions. Logging. And passing configuration via a Reader, the FP way. And I’m skipping State and other properties we may want. So that is our F. The problem is that when you try to use that, it doesn’t even work! Monads don’t compose. That is why we have monad transformers in first place. But which one is the correct stacking?
  9. Also, you want monad transformers? I hope you like this for comprehension. Working with 3 layers of transformer stacked is a nightmare, unwrapping and wrapping monads each step. Please let me guide your attention to the fact this is a single row in the for comprehension. And let’s not even start talking about performance, what all this unwrap-wrap and intermediate objects created do to the jvm.
  10. So, we need a better way. We want to use the interfaces we defined, we like tagless final style, but we don’t want to make our lives hard with all those transformers.
  11. Enter cats-mtl. cats-mtl provides transformer typeclasses for cats' Monads, Applicatives and Functors. The fact that it provides typeclasses is very very important, as typeclasses can be passed around via implicit parameters in our functions.
  12. Cats mtl gives us several type classes for existing monad transformers in cats. Here we have some examples: ApplicativeAsk is the equivalent typeclass for ReaderT, to work with configuration. FunctorRaise, equivalent to EitherT. FunctorTell, to WriterT, for logging. MonadState, equivalent to StateT. And a few more. Note also that the names are descriptive of their capabilities, FunctorTell only requires F to be a Functor to work, following the principle of less power is better.
  13. What does all this mean in practice? It means we can do this. We have a method that requires an implicit typeclass of type FunctorRaise, for our F. Note how much we get in this definition: We know our function can raise errors of type Error We know F can be anything as long as it has an instance of the FunctorRaise typeclass we request All this is checked at compile time, if the implicit doesn’t exist or there are conflicting implicits we will get a compile time error We can test this function in isolation by swapping the implicit we use
  14. Remember our stack before. Let’s implement equivalent type classes to that stack for a dev environment. Here we have the implementation for ApplicativeAsk, hardcoding some configuration. We have an F that must have an Applicative, and we return a hardcoded Config on Ask.
  15. Or we can use this FunctorTell for printing to console when in development. Note that I cheated a bit by making F require applicative as I need ‘pure’.
  16. With those definitions, our previous for comprehension can now become this, a much nicer code. There’s a lot to comment in here. Note that we define our type depending on a single transformer: EitherT. There are ways to remove it, but requires using MonadError and IO, or other IO-equivalent libraries We preserve all the functionality from the old stack via the implicits: configuration, error, logging. All validated at compile time Note we define F as Monad here so we can have flatMap working for the for-comprehension And, note that we have not defined our FunctorRaise anywhere. No, I didn’t forget it, this is not partial code. It’s there, in EitherT. Cats-mtl doesn’t just give us the typeclasses, it also provides default implementations for them, so if I have an EitherT in scope, I get my FunctorRaise, thank you very much. We can test this by providing several implementations of our topic service, but we can also test things like the logging for example, we can provide a witness that stores all the logs instead of printing to console, and at the end of the test we verify they are as we expect.
  17. Ok, so I hope you are convinced that cats-mtl is a good idea. That said, I’d recommend you to use it along this other library: meow-mtl. meow-mtl provides several improvements on top of cats-mtl. - Easy composition of MTL-style functions (I’ll explain this later) MTL instances for cats-effect compatible datatypes (same) One is conflict-free implicits for sub-instances : in the previous code, remember we had to define F as Monad to be able to flatMap? If you have an effect that requires Monad, it derives that automatically for you. Which is neat. Be careful with imports, though, read the readme accurately regarding which imports to use to avoid diverging implicits.
  18. One selling point of meow was ‘Easy composition of MTL-style functions’. Let’s explain it using the example of the documentation of meow. Notice at the top the type AuthRequest, which has 2 elements, Headers and User. We also have 2 functions that depend on MonadState. One on MonadState of User, one on MonadState of Headers. Our handleGreetRequest function depends on MonadState of AuthedRequest, and calls the previous functions. Now, usually this wouldn’t compile, as greetUser and addRequestIdHeader are missing the right implicit. But meow uses Optics and code generation, and it verifies that if we have an AutherRequest, we can get both a Header and a User, so it automatically provides the right implicits to the functions.
  19. Another property was that meow provides MTL instances for cats-effect or monix compatible datatypes. This means you can use those types, which perform better than the monad transformer alternative. See the code in the slide, taken from the readme. Ref is an asynchronous, concurrent mutable reference. meow-mtl provides a MonadState instance for Ref.
  20. In summary, we want MTL because we get all the benefits of a tagless final approach, without the nuisances of monad transformers, and without performance penalties.
  21. And, we are done.