For the past few years in the functional Scala community, the standard approach for adding features to an effect type (features like logging, stateful updates, or accessing config) has been Monad Transformers (EItherT, OptionT, WriterT, ReaderT, etc.).
While elegant and proven, monad transformers were imported directly from Haskell, and in Scala, they have poor ergonomics and poor performance. Using tagless-final on transformers can eliminate some of the boilerplate, but cannot improve performance, and tagless-final makes it insanely hard to locally introduce and eliminate features.
In this presentation, John will introduce an alternate approach he coined ‘effect rotation’, which shares most of the power of monad transformers, but with better ergonomics and no loss of performance. You will see how to use the ZIO library that John created to composably add different features into the ZIO effect type, to solve the same problems as monad transformers, but in a way that feels natural and idiomatic for Scala.
ZIO: Powerful and Principled Functional Programming in ScalaWiem Zine Elabidine
This is an introduction of purely functional programming type safe abstractions that provide a variety of features for building asynchronous and concurrent applications data structures built on ZIO.
You'll learn by examples about the power of functional programming to solve the hard problems of software development in a principled, without compromises.
(download for flawless quality) State Monad - Learn how it works - Follow Alvin Alexander’s example-driven build up to the State Monad and then branch off into a detailed look at its inner workings.
download for better quality - Learn how to use an Applicative Functor to handle multiple independent effectful values through the work of Sergei Winitzki, Runar Bjarnason, Paul Chiusano, Debasish Ghosh and Adelbert Chang
Blazing Fast, Pure Effects without Monads — LambdaConf 2018John De Goes
Effect monads like IO are the way functional programmers interact with the real world. Yet, monadic effects in programming languages like Scala often perform poorly compared to their Haskell counterparts—as much as 10x slower in some benchmarks. In this presentation, John A. De Goes, author of the Scalaz 8 effect system, dredges up an old paper to cast new light on the question of how to model effects, and comes to the surprising conclusion that in Scala, monads may not be the fastest way to model purely functional effects. Join John as he shows a new model of effects that offers performance improvements without sacrificing the wonderful purity that functional programmers rely on to reason about their software.
download for better quality - Learn about the sequence and traverse functions
through the work of Runar Bjarnason and Paul Chiusano, authors of Functional Programming in Scala https://www.manning.com/books/functional-programming-in-scala
At the heart of data processing, event-sourcing, actors, and much more is the queue—a data structure that allows producers to pass work to consumers in a flexible way. On the JVM, most libraries, including Akka, are powered by Java concurrent queues, which are reliable but were designed in a different era, for synchronous (blocking) procedural code. In this presentation, John A. De Goes—architect of the Scalaz 8 effect system—introduces IOQueue, a new type of queue powered by the Scalaz 8 IO monad. IOQueue never blocks and provides seamless, composable back-pressure across an entire application, without users having to think about the problem or write any special code. John will discuss how IOQueue achieves these remarkable properties, and show how the structure can be used to solve hard problems with just a few lines of type-safe, leak-free, composable Scala code. Come learn about the power of Scalaz to solve the hard problems of software development, in a principled way, without compromises.
Introduces the functional programming ideas of Functor, Apply, Applicative And Monad. Shows how to implement each in Scala with Scalaz and how to validate the implementation using property based test using specs2 and scalacheck.
ZIO: Powerful and Principled Functional Programming in ScalaWiem Zine Elabidine
This is an introduction of purely functional programming type safe abstractions that provide a variety of features for building asynchronous and concurrent applications data structures built on ZIO.
You'll learn by examples about the power of functional programming to solve the hard problems of software development in a principled, without compromises.
(download for flawless quality) State Monad - Learn how it works - Follow Alvin Alexander’s example-driven build up to the State Monad and then branch off into a detailed look at its inner workings.
download for better quality - Learn how to use an Applicative Functor to handle multiple independent effectful values through the work of Sergei Winitzki, Runar Bjarnason, Paul Chiusano, Debasish Ghosh and Adelbert Chang
Blazing Fast, Pure Effects without Monads — LambdaConf 2018John De Goes
Effect monads like IO are the way functional programmers interact with the real world. Yet, monadic effects in programming languages like Scala often perform poorly compared to their Haskell counterparts—as much as 10x slower in some benchmarks. In this presentation, John A. De Goes, author of the Scalaz 8 effect system, dredges up an old paper to cast new light on the question of how to model effects, and comes to the surprising conclusion that in Scala, monads may not be the fastest way to model purely functional effects. Join John as he shows a new model of effects that offers performance improvements without sacrificing the wonderful purity that functional programmers rely on to reason about their software.
download for better quality - Learn about the sequence and traverse functions
through the work of Runar Bjarnason and Paul Chiusano, authors of Functional Programming in Scala https://www.manning.com/books/functional-programming-in-scala
At the heart of data processing, event-sourcing, actors, and much more is the queue—a data structure that allows producers to pass work to consumers in a flexible way. On the JVM, most libraries, including Akka, are powered by Java concurrent queues, which are reliable but were designed in a different era, for synchronous (blocking) procedural code. In this presentation, John A. De Goes—architect of the Scalaz 8 effect system—introduces IOQueue, a new type of queue powered by the Scalaz 8 IO monad. IOQueue never blocks and provides seamless, composable back-pressure across an entire application, without users having to think about the problem or write any special code. John will discuss how IOQueue achieves these remarkable properties, and show how the structure can be used to solve hard problems with just a few lines of type-safe, leak-free, composable Scala code. Come learn about the power of Scalaz to solve the hard problems of software development, in a principled way, without compromises.
Introduces the functional programming ideas of Functor, Apply, Applicative And Monad. Shows how to implement each in Scala with Scalaz and how to validate the implementation using property based test using specs2 and scalacheck.
Left and Right Folds- Comparison of a mathematical definition and a programm...Philip Schwarz
We compare typical definitions of the left and right fold functions, with their mathematical definitions in Sergei Winitzki’s upcoming book: The Science of Functional Programming.
Errata:
Slide 13: "The way 𝑓𝑜𝑙𝑑𝑙 does it is by associating to the right" - should, of course ,end in "to the left".
The Functional Programming Triad of Map, Filter and FoldPhilip Schwarz
This slide deck is my homage to SICP, the book which first introduced me to the Functional Programming triad of map, filter and fold.
It was during my Computer Science degree that a fellow student gave me a copy of the first edition, not long after the book came out.
I have not yet come across a better introduction to these three functions.
The upcoming slides are closely based on the second edition of the book, a free online copy of which can be found here:
https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book.html.
Download for original image quality.
Errata:
slide 20: the Clojure map function is in fact the Scheme one repeated - see code below for correction.
Scheme code: https://github.com/philipschwarz/the-fp-triad-of-map-filter-and-fold-scheme
Clojure code: https://github.com/philipschwarz/the-fp-triad-of-map-filter-and-fold-clojure
Some parts of our applications don't need to be asynchronous or interact with the outside world: it's enough that they are stateful, possibly with the ability to handle failure, context, and logging. Although you can use ZIO 2 or monad transformers for this task, both come with drawbacks. In this presentation, Jorge Vásquez will introduce you to ZPure, a data type from ZIO Prelude, which lets you scale back on the power of ZIO 2, but with the same high-performance, type-inference, and ergonomics you expect from ZIO 2 libraries.
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Philip Schwarz
(download for best quality slides) Gain a deeper understanding of why right folds over very large and infinite lists are sometimes possible in Haskell.
See how lazy evaluation and function strictness affect left and right folds in Haskell.
Learn when an ordinary left fold results in a space leak and how to avoid it using a strict left fold.
This version eliminates some minor imperfections and corrects the following two errors:
slide 15: "as sharing is required" should be "as sharing is not required"
slide 43: 푠푓표푙푑푙 (⊕) 푎 should be 푠푓표푙푑푙 (⊕) 푒
As a part of kotlinx.coroutines 1.2 Flow was introduced as a cold asynchronous data stream. How does it work? What we can do with it? Is it that we waiting so long for replacing Rx? The talk has answers to them.
Purely functional libraries like ZIO can help you build high-performance, concurrent applications that don’t have deadlocks, don’t leak resources using purely functional code.
In this talk, Wiem will walk you through how to build a control system for the elevators at a fictional hotel, H&A Hotel. You’ll learn how to use basic control structures like Ref, Queue, STM and ZIO to build real world software.
ZIO-Direct allows direct style programming with ZIO. This library provides a *syntactic sugar* that is more powerful than for-comprehensions as well as more natural to use. Simply add the `.run` suffix to any ZIO effect in order to retrieve it's value.
Jetpack Compose - Android’s modern toolkit for building native UIGilang Ramadhan
Jetpack Compose simplifies and accelerates UI development on Android. Quickly bring your app to life with less code, powerful tools, and intuitive Kotlin APIs.
"The joy of Scala" - Maxim Novak / Wix
Around eight years ago I started my journey as a developer. Since then, I've played around with many languages and thought that C# offers the best developer productivity. After joining Wix two years ago, I was exposed to the amazing world of Scala and Functional Programming and never looked back.
In Scala the code is much more concise, less ceremonious, immutable by default, combines functional with object oriented, seamlessly interoperates with Java, and many software engineering patterns are already baked into the language. Most importantly - Scala is FUN! By the end of the session you too will, hopefully, convert to Scala and never look back.
Recording of the lecture (Hebrew) - https://youtu.be/TcnYTwff2xU
Boost your productivity with Scala tooling!MeriamLachkar1
Our rich ecosystem provides developers with powerful tools that improve productivity on small or huge projects.
In this talk, I will present the tools that allow me to focus on my projects by making tedious tasks easier. From bootstrapping projects, to code linting and refactoring, from continuous integration and automatic publication and documentation rendering, come discover my favorite tools.
Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...Philip Schwarz
Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Haskell, Scala and Java.
Inspired by the example in Scott Wlaschin’s F# book: Domain Modeling Made Functional.
Download for better results.
Java 19 Code: https://github.com/philipschwarz/fruit-salad-and-fruit-snack-ADT-example-java
Arriving at monads by going from pure-function composition to effectful-funct...Philip Schwarz
download for better quality - Arrive at monads by going from pure-function composition to effectful-function composition - I made some summary/overview slides of Rob Norris' (https://twitter.com/tpolecat) very interesting talk: "Functional Programming with Effects" https://www.youtube.com/watch?v=po3wmq4S15
He starts from pure function composition and uses math to derive Kleisli composition and Monad.
download for better quality - Learn about the sequence and traverse functions
through the work of Runar Bjarnason and Paul Chiusano, authors of Functional Programming in Scala https://www.manning.com/books/functional-programming-in-scala, and others (Martin Odersky, Derek Wyatt, Adelbert Chang)
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1Philip Schwarz
slides can look grainy and/or out of focus when seen on slideshare - download for flawless quality - Based on Scott Wlaschin’s great book 'Domain Modeling Made Functional' and on Martin Odersky's talk 'A Tour of Scala 3'.
Function Programming in Scala.
A lot of my examples here comes from the book
Functional programming in Scala By Paul Chiusano and Rúnar Bjarnason, It is a good book, buy it.
ZIO provides a variety of features for building synchronous, asynchronous and concurrent applications and enables us to use functional effects in Scala.
- Why functional effects?
- How to use functional effects and data types built on ZIO?
- How to manage errors and recover from them?
- How to manage resources and how to make concurrent tasks?
Left and Right Folds- Comparison of a mathematical definition and a programm...Philip Schwarz
We compare typical definitions of the left and right fold functions, with their mathematical definitions in Sergei Winitzki’s upcoming book: The Science of Functional Programming.
Errata:
Slide 13: "The way 𝑓𝑜𝑙𝑑𝑙 does it is by associating to the right" - should, of course ,end in "to the left".
The Functional Programming Triad of Map, Filter and FoldPhilip Schwarz
This slide deck is my homage to SICP, the book which first introduced me to the Functional Programming triad of map, filter and fold.
It was during my Computer Science degree that a fellow student gave me a copy of the first edition, not long after the book came out.
I have not yet come across a better introduction to these three functions.
The upcoming slides are closely based on the second edition of the book, a free online copy of which can be found here:
https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book.html.
Download for original image quality.
Errata:
slide 20: the Clojure map function is in fact the Scheme one repeated - see code below for correction.
Scheme code: https://github.com/philipschwarz/the-fp-triad-of-map-filter-and-fold-scheme
Clojure code: https://github.com/philipschwarz/the-fp-triad-of-map-filter-and-fold-clojure
Some parts of our applications don't need to be asynchronous or interact with the outside world: it's enough that they are stateful, possibly with the ability to handle failure, context, and logging. Although you can use ZIO 2 or monad transformers for this task, both come with drawbacks. In this presentation, Jorge Vásquez will introduce you to ZPure, a data type from ZIO Prelude, which lets you scale back on the power of ZIO 2, but with the same high-performance, type-inference, and ergonomics you expect from ZIO 2 libraries.
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Philip Schwarz
(download for best quality slides) Gain a deeper understanding of why right folds over very large and infinite lists are sometimes possible in Haskell.
See how lazy evaluation and function strictness affect left and right folds in Haskell.
Learn when an ordinary left fold results in a space leak and how to avoid it using a strict left fold.
This version eliminates some minor imperfections and corrects the following two errors:
slide 15: "as sharing is required" should be "as sharing is not required"
slide 43: 푠푓표푙푑푙 (⊕) 푎 should be 푠푓표푙푑푙 (⊕) 푒
As a part of kotlinx.coroutines 1.2 Flow was introduced as a cold asynchronous data stream. How does it work? What we can do with it? Is it that we waiting so long for replacing Rx? The talk has answers to them.
Purely functional libraries like ZIO can help you build high-performance, concurrent applications that don’t have deadlocks, don’t leak resources using purely functional code.
In this talk, Wiem will walk you through how to build a control system for the elevators at a fictional hotel, H&A Hotel. You’ll learn how to use basic control structures like Ref, Queue, STM and ZIO to build real world software.
ZIO-Direct allows direct style programming with ZIO. This library provides a *syntactic sugar* that is more powerful than for-comprehensions as well as more natural to use. Simply add the `.run` suffix to any ZIO effect in order to retrieve it's value.
Jetpack Compose - Android’s modern toolkit for building native UIGilang Ramadhan
Jetpack Compose simplifies and accelerates UI development on Android. Quickly bring your app to life with less code, powerful tools, and intuitive Kotlin APIs.
"The joy of Scala" - Maxim Novak / Wix
Around eight years ago I started my journey as a developer. Since then, I've played around with many languages and thought that C# offers the best developer productivity. After joining Wix two years ago, I was exposed to the amazing world of Scala and Functional Programming and never looked back.
In Scala the code is much more concise, less ceremonious, immutable by default, combines functional with object oriented, seamlessly interoperates with Java, and many software engineering patterns are already baked into the language. Most importantly - Scala is FUN! By the end of the session you too will, hopefully, convert to Scala and never look back.
Recording of the lecture (Hebrew) - https://youtu.be/TcnYTwff2xU
Boost your productivity with Scala tooling!MeriamLachkar1
Our rich ecosystem provides developers with powerful tools that improve productivity on small or huge projects.
In this talk, I will present the tools that allow me to focus on my projects by making tedious tasks easier. From bootstrapping projects, to code linting and refactoring, from continuous integration and automatic publication and documentation rendering, come discover my favorite tools.
Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...Philip Schwarz
Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Haskell, Scala and Java.
Inspired by the example in Scott Wlaschin’s F# book: Domain Modeling Made Functional.
Download for better results.
Java 19 Code: https://github.com/philipschwarz/fruit-salad-and-fruit-snack-ADT-example-java
Arriving at monads by going from pure-function composition to effectful-funct...Philip Schwarz
download for better quality - Arrive at monads by going from pure-function composition to effectful-function composition - I made some summary/overview slides of Rob Norris' (https://twitter.com/tpolecat) very interesting talk: "Functional Programming with Effects" https://www.youtube.com/watch?v=po3wmq4S15
He starts from pure function composition and uses math to derive Kleisli composition and Monad.
download for better quality - Learn about the sequence and traverse functions
through the work of Runar Bjarnason and Paul Chiusano, authors of Functional Programming in Scala https://www.manning.com/books/functional-programming-in-scala, and others (Martin Odersky, Derek Wyatt, Adelbert Chang)
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1Philip Schwarz
slides can look grainy and/or out of focus when seen on slideshare - download for flawless quality - Based on Scott Wlaschin’s great book 'Domain Modeling Made Functional' and on Martin Odersky's talk 'A Tour of Scala 3'.
Function Programming in Scala.
A lot of my examples here comes from the book
Functional programming in Scala By Paul Chiusano and Rúnar Bjarnason, It is a good book, buy it.
ZIO provides a variety of features for building synchronous, asynchronous and concurrent applications and enables us to use functional effects in Scala.
- Why functional effects?
- How to use functional effects and data types built on ZIO?
- How to manage errors and recover from them?
- How to manage resources and how to make concurrent tasks?
Introduction to how to test our programs using imperative programming and functional programming with Tagless Final technique and how to make it simpler using ZIO. ZIO provides many features for concurrency and asynchronous programs. This presentation is about how to use ZIO environment to test your application.
With my simple implementation I wanted to demonstrate the basic ideas of th IO Monad.
My impl of the IO Monad is just a feasibility study, not production code!
When coding my impl of IO I was very much inspired by cats.effect.IO and monix.eval.Task which I studied at that time. Both are implementions of the IO Monad.
The API of my IO is very similar to the basics of Monix Task. This IO implementation also helped me to understand the IO Monad (of cats-effect) and Monix Task.
Interop with Future is also supported. You can convert IO to a Future. Vice versa you can convert a Future to an IO.
The development of my impl can be followed step by step in the code files in package iomonad.
Functional programming in Scala. Looking at various examples of defining a program first and executing it at some later stage, separating pure functions from side effects.
Function Programming in Scala.
A lot of my examples here comes from the book
Functional programming in Scala By Paul Chiusano and Rúnar Bjarnason, It is a good book, buy it.
Algebraic Thinking for Evolution of Pure Functional Domain ModelsDebasish Ghosh
The focus of the talk is to emphasize the importance of algebraic thinking when designing pure functional domain models. The talk begins with the definition of an algebra as consisting of a carrier type, a set of operations/functions and a set of laws on those operations. Using examples from the standard library, the talk shows how thinking of abstractions in terms of its algebra is more intuitive than discussing its operational semantics. The talk also discusses the virtues of parametricity and compositionality in designing proper algebras.
Algebras are compositional and help build larger algebras out of smaller ones. We start with base level types available in standard libraries and compose larger programs out of them. We take a real life use case for a domain model and illustrate how we can define the entire model using the power of algebraic composition of the various types. We talk about how to model side-effects as pure abstractions using algebraic effects. At no point we will talk about implementations.
At the end of the talk we will have a working model built completely out of the underlying algebra of the domain language.
Actors and functional_reactive_programmingDiego Alonso
Slides from my presentation in the Typelevel Summit held in Lausanne, on the 14th of June 2019.
It introduces an implementation of Functional Reactive Programming, using an analogy with actors.
Kotlin For Android - Functions (part 3 of 7)Gesh Markov
This presentation is part of a workshop series.
In this section you will learn about operators, inlining, a little bit about generics, named parameters, lambdas and closures, obtaining references to functions and passing them to other functions, and higher-order functions.
License:
This presentation is licensed under the Creative Commons, No Derivatives, Version 3.0 US: https://creativecommons.org/licenses/by-nd/3.0/us/legalcode
Function Programming in Scala.
A lot of my examples here comes from the book
Functional programming in Scala By Paul Chiusano and Rúnar Bjarnason, It is a good book, buy it.
Download for better quality.
Monads do not Compose. Not in a generic way - There is no general way of composing monads.
A comment from Rúnar Bjarnason, coauthor of FP in Scala: "They do compose in a different generic way. For any two monads F and G we can take the coproduct which is roughly Free of Either F or G (up to normalization)".
Another comment from Sergei Winitzki (which caused me to upload https://www.slideshare.net/pjschwarz/addendum-to-monads-do-not-compose): "It is a mistake to think that a traversable monad can be composed with another monad. It is true that, given `Traversable`, you can implement the monad's methods (pure and flatMap) for the composition with another monad (as in your slides 21 to 26), but this is a deceptive appearance. The laws of the `Traversable` typeclass are far insufficient to guarantee the laws of the resulting composed monad. The only traversable monads that work correctly are Option, Either, and Writer. It is true that you can implement the type signature of the `swap` function for any `Traversable` monad. However, the `swap` function for monads needs to satisfy very different and stronger laws than the `sequence` function from the `Traversable` type class. I'll have to look at the "Book of Monads"; but, if my memory serves, the FPiS book does not derive any of these laws." See https://www.linkedin.com/feed/update/urn:li:groupPost:41001-6523141414614814720?commentUrn=urn%3Ali%3Acomment%3A%28groupPost%3A41001-6523141414614814720%2C6532108273053761536%29
Why functional programming and category theory strongly mattersPiotr Paradziński
Abstractions of Category Theory to define abstractions (Functor, Applicative, Monad, Comonad, Coyoneda) commonly used in functional programming (FP). Using definitions from Category Theory to reason about modular and composable design. Examples based on Haskell papers: Functional pearls translated to Scala.
Why functional programming and category theory strongly matters - Piotr Parad...Scalac
Niektórzy twierdzą, że SOLID w extremalnej postaci to właśnie FP, Greg Young twierdzi, że CQRS i ES to jest FP.
Programiści FP utrzymują, że Design Patterns są potrzebne, bo w OOP brakuje pewnych konstrukcji.
Sami używają abstrakcji matematycznych z teorii kategorii w sposób zbliżony do wzorców.
Opowiem czym jest FP i jakie supermoce daje.
Pokażę abstrakcje matematyczne z teorii kategorii: Category, Functor, Natural transformation, Monad.
Jak zostały one wykorzystane w oryginalnych publikacjach (functional pearls) używając języka Scala.
(Znajomość Scala nie jest potrzebna.)
Pokaże, też inne często używane w FP abstrakcje z algebry abstrakcyjnej (Monoid, Semigroup, Foldable, Traversable).
Dam też, przegląd mniej znanych ale bardzo ciekawych abstrakcji z teorii kategorii: Comonad, Contravariant, Bifunctor, Profunctor
oraz konstrukcji: Product, Coproduct, Free, Coyoneda.
Myślę, że zarówno doświadczeni programiści jak i osoby nowe dostaną solidną porcję nowych narzędzi do pisania i projektowania oprogramowania.
Może, uda się zobaczyć wzorce projektowe i dobre zasady OOP w nowym świetle :)
For decades, the Functor, Monoid, and Foldable type class hierarchies have dominated functional programming. Implemented in libraries like Scalaz and Cats, these type classes have an ancient origin in Haskell, and they have repeatedly proven useful for advanced functional programmers, who use them to maximize code reuse and increase code correctness.
Yet, as these type classes have been copied into Scala and aged, there is a growing awareness of their drawbacks, ranging from being difficult to teach to weird operators that don’t make sense in Scala (ap from Applicative), to overlapping and lawless type classes (Semigroupal), to a complete inability to abstract over data types that possess related structure (such as isomorphic applicatives).
In this presentation, John A. De Goes introduces a new Scala library with a completely different factoring of functional type classes—one which throws literally everything away and starts from a clean slate. In this new factoring, type classes leverage Scala’s strengths, including variance and modularity. Pieces fit together cleanly and uniformly, and in a way that satisfies existing use cases, but enables new ones never before possible. Finally, type classes are named, organized, and described in a way that makes teaching them easier, without compromising on algebraic principles.
If you’ve ever thought functional type classes were too impractical or too confusing or too restrictive, now’s your chance to get a fresh perspective on a library that just might make understanding functional programming easier than ever before!
Modern applications are concurrent, parallel, asynchronous, and synchronous; they utilize many different subsystems, including network systems, actor systems, distributed systems, and more. Across all these modes of computation and different subsystems, the one constant is failure. Errors happen everywhere, and taming their monstrous complexity in a way that helps developers write correct code and troubleshoot failures is one of the hardest challenges of modern application development.
In this presentation, created just for the Dublin Scala Meetup, John A. De Goes and Kai from 7mind.io will take attendees on a tour of error management in Scala, comparing and contrasting Scala's own Future type, and the ZIO effect type. You'll see how functional effects provide features that go way beyond Future: including unified errors across all modes of computation, powerful error operators, lossless error propagation, compiler-assisted error handling, and a stunning new feature for debugging, sponsored by Irish consultancy 7mind.io, will be unveiled exclusively at this presentation.
Come learn about how modern functional effect systems like ZIO provide compelling new solutions to the problems of everyday error management.
Moore's Law may be dead, but CPUs acquire more cores every year. If you want to minimize response latency in your application, you need to use every last core - without wasting resources that would destroy performance and throughput. Traditional locks grind threads to a halt and are prone to deadlocks, and although actors provide a saner alternative, they compose poorly and are at best weakly-typed.
In this presentation, created exclusively for Scalar Conf, John reveals a new alternative to the horrors of traditional concurrency, directly comparing it to other leading approaches in Scala. Witness the beauty, simplicity, and power of declarative concurrency, as you discover how functional programming is the most practical solution to solving the tough challenges of concurrency.
Final tagless. The topic strikes fear into the hearts of Scala developers everywhere—and not without reason. Final tagless allows developers to build composable Domain Specific Languages (DSLs) that model interaction with the outside world. Programs written using the final tagless style can be tested deterministically and reasoned about at compile-time. Yet the technique requires confusing, compiler-choking higher-kinded types, like `F[_]`, and pervasive, non-inferable context bounds like `F[_]: Concurrent: Console: Logging`. Many have looked at final tagless and wondered if all the layers of complexity and ceremony are really worth the benefits.
In this presentation, John A. De Goes provides a gentle and accessible introduction to final tagless, explaining what it is and the problem it intends to solve. John shows that while final tagless is easier to use than free monads, the technique suffers from a litany of drawbacks that push developers away from functional programming in Scala. John then introduces a novel approach that shares some of the benefits of final tagless, but which is idiomatic Scala, easy to explain, doesn’t need any complex type machinery, provides flawless type inference, and works beautifully across Scala 2.x and Scala 3.
Come join John for an evening of fun as you learn how to write functional code in Scala that's easy to test and easy to reason about—all without the complexity of free monads or final tagless.
Scalaz-stream introduced the Scala ecosystem to purely functional streams. Although widely deployed in production at Verizon, SlamData, and elsewhere, the last release of scalaz-stream was October 23rd, 2016, and newer projects such as FS2, Monix Iterant, and others have risen to fill the gap, each addressing different use cases in the functional programming community. In this talk, John A. De Goes, architect of the Scalaz 8 effect system, unveils a new design for a next-generation version of scalaz-stream. Designed to embrace the powerful features of the Scalaz 8 effect system—features not available in any other effect type—this design features higher-performance, stronger guarantees, and far less code than previous incarnations. You are invited to discover the practicality of functional programming, as well as its elegance, beauty, and composability, in this unique presentation available exclusively at Scale By the Bay.
Scalaz-stream introduced the Scala ecosystem to purely functional streams. Although widely deployed in production at Verizon, SlamData, and elsewhere, the last release of scalaz-stream was October 23rd, 2016, and newer projects such as FS2, Monix Iterant, and others have risen to fill the gap, each addressing different use cases in the functional programming community. In this talk, John A. De Goes, architect of the Scalaz 8 effect system, unveils a new design for a next-generation version of scalaz-stream. Designed to embrace the powerful features of the Scalaz 8 effect system—features not available in any other effect type—this design features higher-performance, stronger guarantees, and far less code than previous incarnations. You are invited to discover the practicality of functional programming, as well as its elegance, beauty, and composability, in this unique presentation available exclusively at Scale By the Bay.
ZIO Schedule: Conquering Flakiness & Recurrence with Pure Functional ProgrammingJohn De Goes
As professional software engineers, sometimes messy details of the real world stand in the way of us delivering principled software. Flaky connections, unreliable services, and bulletproof job scheduling in the presence of non-determinism and failure all tricky problems that discourage us from writing principled software. Yet sometimes the shortcuts we take to solve these problems result in downtime for the business and sleepless nights for us.
In this brand-new presentation, created exclusively for Scala in the City, John A. De Goes will show how functional programming can help bring order to even the most chaotic systems. Using ZIO, a new zero-dependency Scala library for building massively scalable asynchronous and concurrent applications, John will demonstrate how functional programming leverages reified effects and algebras to solve the trickiest of reliability and scheduling problems in a principled, composable, flexible way.
Join John for an evening of fun and functional programming as you explore fresh ways of thinking about reliability and scheduling, and come out of the talk with valuable skills for using ZIO to solve the everyday problems you encounter at work.
Scalaz 8 is the latest edition of the popular functional programming library for Scala. In this whirlwind tour, maintainer John A. De Goes discusses some of the hottest features of Scalaz 8, including all of the following:
* A fast, concurrent, and leak-free effect system, which has small, composable, and powerful primitives for building practical, real-world software;
* A non-linear type class hierarchy, which permits a more powerful hierarchy that infers well without devastating ambiguous implicit errors;
* A new encoding for abstractions in category theory that providers higher fidelity and enables new categories of useful software to be developed;
* A Scala 2.12 encoding of opaque types that powers improved performance and better developer UX.
In this tour, you’ll see how the design of Scalaz 8 was inspired by a desire to provide Scala developers with a principled, performant, and pragmatic library that never sacrifices the safety and equational reasoning properties of functional programming. You’ll see live code snippets that show you how solving complex real world problems is simpler, faster, safer, and more reasonable than in previous versions of Scalaz. And hopefully you’ll be inspired at just how far functional programming in Scala has come in the past decade.
In this presentation, John A. De Goes looks at several concurrency and scalability problems similar to the ones all programmers have to face, and shows how purely functional solutions written using Scalaz 8 are shorter, faster, easier to test, and easier to understand than competing solutions written using Akka actors. Discover how functional programming can be your secret superpower when it comes to quickly building bullet-proof business applications!
Well-architected libraries for functional programming are at once immensely beautiful and practical. They are simple but extraordinarily powerful, helping users solve their problems by snapping together Lego-like building blocks, each of which has just one purpose. Yet, there is a surprising dearth of material on how developers can construct their own well-architected functional code. Many functional programming tutorials talk discuss type safety and making illegal states unrepresentable, but few speak on the subject of good functional interface design.
In this presentation, John A. De Goes takes to the stage to discuss a nebulous and underrated tool in the arsenal of every functional programmer. Called *orthogonality*, this tool allows programmers to craft the building blocks of their functional code at "right angles", so so they can be reasoned about simply and composed predictably to solve complex problems. John introduces the concept of orthogonality, looking at its geometric and algebraic origins, presents a way to measure orthogonality, and then walks through a number of interface examples, comparing non-orthogonal designs with orthogonal ones.
By the end of the session, attendees should have a newfound appreciation for how important orthogonality is to constructing good functional interfaces, and they should develop the early stages of an intuition about how to slice up a complex problem into core, single-purpose, composable building blocks.
The Design of the Scalaz 8 Effect SystemJohn De Goes
Purely functional Scala code needs something like Haskell's IO monad—a construct that allows functional programs to interact with external, effectful systems in a referentially transparent way. To date, most effect systems for Scala have fallen into one of two categories: pure, but slow or inexpressive; or fast and expressive, but impure and unprincipled. In this talk, John A. De Goes, the architect of Scalaz 8’s new effect system, introduces a novel solution that’s up to 100x faster than Future and Cats Effect, in a principled, modular design that ships with all the powerful primitives necessary for building complex, real-world, high-performance, concurrent functional programs.
Thanks to built-in concurrency, high performance, lawful semantics, and rich expressivity, Scalaz 8's effect system may just be the effect system to attract the mainstream Scala developers who aren't familiar with functional programming.
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsJohn De Goes
Quark is a new Scala DSL for data processing and analytics that runs on top of the Quasar Analytics compiler. Quark is adept at processing semi-structured data and compiles query plans to operations that run entirely inside a target data source. In this presentation, John A. De Goes provides an overview of the open source library, showing several use cases in data processing and analytics. John also demonstrates a powerful technique that every developer can use to create their own purely-functional, type-safe DSLs in the Scala programming language.
Free monads and free applicatives have proven an incredibly useful tool in repertoire of the functional programmer: they separate concerns, encourage denotational semantics for program specification, allow easy and type-safe mocking of purely functional code, and allow dynamic introspection and optimization.
Despite these benefits, free monads are notoriously constrained: by themselves, they cannot handle parallelism (only sequentiality), and because they provide only a monad, richer structures (such as monads that fail, or monads that support alternation) cannot be expressed without crude hacks that limit composability and expressiveness.
In this session, John A. De Goes shows how the free monad can be deconstructed for its individual features, and then rebuilt using a more powerful technique that enables more extensibility. The resulting structure — no longer technically a "free monad" — allows reification of as few or as many aspects of computation as are necessary to model the problem domain.
After the session, attendees will know how to augment their existing free programs to add parallelism, racing, failure, and other aspects of computation as required by their problem. In addition, through this thorough deconstruction and reconstruction of the free monad, attendees will have a very deep understanding of reified computation and why the free monad has the structure and limitations it does.
There are many popular stream libraries for Scala developers, including Akka Streams, scalaz-stream, fs2, plus others in the Java ecosystem. While all excellent choices for building reactive Scala applications, their reliance on effects makes them particularly difficult to test and reason about. In this talk, long-time Scala functional programmer John A. De Goes takes to the stage to demonstrate a new approach to modeling streams that requires less machinery and has more reasoning power, composability, flexibility, and testability than many other approaches. By attending the talk, you'll learn how the best stream library may be the one you get for (co)free!
What's the best way to model modular, composable effects in your purely functional program? In this presentation, I take a look at monad transformers and free monads, discuss their history, and compare how effectively they solve the problem.
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...John De Goes
Maybe you've played around with functional programming before, but don't consider yourself a functional programmer. Or maybe you program functionally, but only in a dynamically-typed programming language. Or MAYBE you just like workshops with really long, ridiculously-sounding titles!
No matter, this workshop that teaches the super hot programming language PureScript is guaranteed to cure what ails you!
Come, learn about functions, learn about types, learn about data, and learn about how to smash them all together to build beautiful programs that are easy to test, easy to combine, and easy to reason about.
Become the functional programmer you were born to be!
Halogen is a popular choice for building front-end user-interfaces with PureScript. Often described as a purely functional version of React, Halogen allows building user-interfaces by composing declarative, self-contained components, including effectful components those built from third-party Javascript libraries.
In this presentation, John presents a high-level summary of where Halogen has come from, how it works right now, and what are the main drawbacks to both FRP and React. John then suggests that incremental computation should be the foundation for the next major version of Halogen, and sketches out a possible way of achieving that in a declarative fashion.
All Aboard The Scala-to-PureScript Express!John De Goes
Many Scala programmers have embraced functional programming, but the syntax and semantics of programming languages in the Haskell family remains a mystery. In this talk, Scala developers (and to some extent, Java developers) will see how the types, data structures, traits / interfaces, packages, and so forth translate into their PureScript counterparts.
SlamData - How MongoDB Is Powering a Revolution in Visual AnalyticsJohn De Goes
Slides from my presentation at MongoDB Days Silicon Valley. I discuss what SlamData is, the challenges it had to solve to build an analytics solution in the NoSQL space, and how specific features of MongoDB help power its advanced analytics functionality.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
Connector Corner: Automate dynamic content and events by pushing a button
One Monad to Rule Them All
1. One Monad to Rule
Them All
Functional JVM Meetup
Prague, Aug 8 2019
John A. De Goes — @jdegoes
2. Agenda
1. INTRO TO
FUNCTIONAL EFFECTS
2
2. TOUR OF THE
EFFECT ZOO
3. VERTICAL
EFFECT COMPOSITION
4. INTRO TO
EFFECT ROTATION
5. PRACTICE OF
EFFECT ROTATION
4. 1. Intro to Functional Effects
4
World of Values
Variables
Remove Duplication
In a Single Expression
Functions
Remove Duplication
Across Multple
Expressions
Combinators
Remove Higher-Order
Duplication Across
Expressions
Testing
Test Values for
Equality, Similarity,
Inequality
5. 1. Intro to Functional Effects
5
World of Values
Variables
Remove Duplication
In a Single Expression
Functions
Remove Duplication
Across Multple
Expressions
Combinators
Remove Higher-Order
Duplication Across
Expressions
Testing
Test Values for
Equality, Similarity,
Inequality
6. 1. Intro to Functional Effects
6
World of Values
Variables
Remove Duplication
In a Single Expression
Functions
Remove Duplication
Across Multple
Expressions
Combinators
Remove Higher-Order
Duplication Across
Expressions
Testing
Test Values for
Equality, Similarity,
Inequality
7. 1. Intro to Functional Effects
7
World of Values
Variables
Remove Duplication
In a Single Expression
Functions
Remove Duplication
Across Multple
Expressions
Combinators
Remove Higher-Order
Duplication Across
Expressions
Testing
Test Values for
Equality, Similarity,
Inequality
8. 1. Intro to Functional Effects
8
World of Values
Variables
Remove Duplication
In a Single Expression
Functions
Remove Duplication
Across Multple
Expressions
Combinators
Remove Higher-Order
Duplication Across
Expressions
Testing
Test Values for
Equality, Similarity,
Inequality
Cases
Packages
Types
Fields
Input/Output
Methods
11. 1. Intro to Functional Effects
11
sealed trait Alarm[+A]
case class Return [A](v : A) extends Alarm[A]
case class CheckTripped[A](f : Boolean => Alarm[A]) extends Alarm[A]
case class Call [A](next: Alarm[A]) extends Alarm[A]
val check: Alarm[Boolean] =
CheckTripped(tripped =>
if (tripped) Call(Return(true)) else Return(false))
12. 1. Intro to Functional Effects
12
● GO RUNNING
Execution
(Interpretation)
13. 1. Intro to Functional Effects
13
def interpret[A](alarm: Alarm[A]): A = alarm match {
case Return(v) => v
case CheckTripped(f) => interpret(f(sensor.tripped))
case Call(next) => securityCompany.call(); interpret(next)
}
14. 1. Intro to Functional Effects
14
"A functional effect is an immutable data type equipped with a set
of core operations that together provide a complete, type-safe
model of a domain concern."
— John A. De Goes
15. 1. Intro to Functional Effects
15
For every concern, there is a functional effect
Concern Effect Execution
Optionality Option[A] null or A
Disjunction Either[A, B] A or B
Nondeterminism List[A] Option[A]
Input/Output IO[A] throw or A
17. 17
A functional effect for optionality
Maybe[A]
Succeeds with values of type A
1. Intro to Functional Effects
18. 18
A functional effect for optionality
Operation Signature
Present A => Maybe[A]
Absent Maybe[Nothing]
Map (Maybe[A], A => B) => Maybe[B]
Chain (Maybe[A], A => Maybe[B]) => Maybe[B]
1. Intro to Functional Effects
19. 19
sealed trait Maybe[+A]
case class Present[A](value: A) extends Maybe[A]
case object Absent extends Maybe[Nothing]
case class Map[A, B](maybe: Maybe[A], mapper: A => B) extends Maybe[B]
case class Chain[A, B](first: Maybe[A], callback: A => Maybe[B]) extends Maybe[B]
A functional effect for optionality
1. Intro to Functional Effects
20. 20
sealed trait Maybe[+A] { self =>
def map[B](f: A => B): Maybe[B] = Map(self, f)
def flatMap[B](f: A => Maybe[B]): Maybe[B] = Chain(self, f)
}
object Maybe {
def present[A](value: A): Maybe[A] = Present[A]
val absent: Maybe[Nothing] = Absent
}
A functional effect for optionality
1. Intro to Functional Effects
21. def interpret[Z, A](ifAbsent: Z, f: A => Z)(maybe: Maybe[A]): Z =
maybe match {
case Present(a) => f(a)
case Absent => ifAbsent
case Map(old, f0) => interpret(ifAbsent, f.compose(f0))(old)
case Chain(old, f) =>
interpret(ifAbsent, a => interpret(ifAbsent, f)(f(a)))(old)
}
21
A functional effect for optionality
1. Intro to Functional Effects
22. 22
Core operations for functional effects
Operation Signature Functional Type Class
pure / point A => F[A] Applicative
empty / zero F[Nothing] MonadPlus
map (F[A], A => B) => F[B] Functor
flatMap (F[A], A => F[B]) => F[B] Monad
zip / ap [F[A], F[B]) => F[(A, B)] Apply
1. Intro to Functional Effects
23. 23
For comprehension syntax for monadic effects
1. Intro to Functional Effects
for {
user <- lookupUser(userId)
profile <- user.profile
pic <- profile.picUrl
} yield pic
lookupUser(userId).flatMap(user =>
user.profile.flatMap(profile =>
profile.picUrl.map(pic =>
pic)))
25. 25
The functional effect of optionality
2. Tour of the Effect Zoo
sealed trait Option[+A]
final case class Some[+A](value: A) extends Option[A]
case object None extends Option[Nothing]
Option[A]
26. 26
The functional effect of optionality
2. Tour of the Effect Zoo
// Core operations:
def some[A](v: A): Option[A] = Some(a)
val none: Option[Nothing] = None
def map[A, B](o: Option[A], f: A => B): Option[B]
def flatMap[B, B](o: Option[A], f: A => Option[B]): Option[B]
// Execution / Interpretation:
def fold[Z](z: Z)(f: A => Z)(o: Option[A]): Z
Option[A]
27. 27
The functional effect of optionality
2. Tour of the Effect Zoo
for {
user <- lookupUser(userId)
profile <- user.profile
pic <- profile.picUrl
} yield pic
Option[A]
28. 28
The functional effect of failure
2. Tour of the Effect Zoo
sealed trait Either[+E, +A]
final case class Left[+E](value: E) extends Either[E, Nothing]
case class Right[+A](value: A) extends Eitherr[Nothing, A]
Either[E, A]
29. 29
The functional effect of failure
2. Tour of the Effect Zoo
Either[E, A]
// Core operations:
def left[E](e: E): Either[E, Nothing] = Left(e)
def right[A](a: A): Either[Nothing, A] = Right(a)
def map[E, A, B](o: Either[E, A], f: A => B): Either[E, B]
def flatMap[E, A, B](o: Either[E, A], f: A => Either[E, B]): Either[E, B]
// Execution / Interpretation:
def fold[Z, E, A](left: E => Z, right: A => Z)(e: Either[E, A]): Z
30. 30
The functional effect of failure
2. Tour of the Effect Zoo
for {
user <- decodeUser(json1)
profile <- decodeProfile(json2)
pic <- decodeImage(profile.encPic)
} yield (user, profile, pic)
Either[E, A]
31. 31
The functional effect of logging
2. Tour of the Effect Zoo
final case class Writer[+W, +A](run: (Vector[W], A))
Writer[W, A]
32. 32
The functional effect of logging
2. Tour of the Effect Zoo
Writer[W, A]
// Core operations:
def pure[A](a: A): Writer[Nothing, A] = Writer((Vector(), a))
def write[W](w: W): Writer[W, Unit] = Writer((Vector(w), ()))
def map[W, A, B](o: Writer[W, A], f: A => B): Writer[W, B]
def flatMap[W, A, B](o: Writerr[W, A], f: A => Writer[W, B]): Writer[W, B]
// Execution / Interpretation:
def run[W, A](writer: Writer[W, A]): (Vector[W], A)
33. 33
The functional effect of logging
2. Tour of the Effect Zoo
for {
user <- pure(findUser())
_ <- log(s"Got user: $user")
_ <- pure(getProfile(user))
_ <- log(s"Got profile: $profile")
} yield user
Writer[W, A]
34. 34
The functional effect of state
2. Tour of the Effect Zoo
final case class State[S, +A](run: S => (S, A))
State[S, A]
35. 35
The functional effect of state
2. Tour of the Effect Zoo
State[S, A]
// Core operations:
def pure[S, A](a: A): State[S, A] = State[S, A](s => (s, a))
def get[S]: State[S, S] = State[S, S](s => (s, s))
def set[S](s: S): State[S, Unit] = State[S, S](_ => (s, ()))
def map[S, A, B](o: State[S, A], f: A => B): State[S, B]
def flatMap[S, A, B](o: State[S, A], f: A => State[S, B]): State[S, B]
// Execution / Interpretation:
def run[S, A](s: S, state: State[S, A]): (S, A)
36. 36
The functional effect of state
2. Tour of the Effect Zoo
for {
_ <- set(0)
v <- get
_ <- set(v + 1)
v <- get
} yield v
State[S, A]
37. 37
The functional effect of reader
2. Tour of the Effect Zoo
final case class Reader[-R, +A](run: R => A)
Reader[R, A]
38. 38
The functional effect of reader
2. Tour of the Effect Zoo
Reader[R, A]
// Core operations:
def pure[A](a: A): Reader[Any, A] = Reader[Any, A](_ => a)
def environment: Reader[R, R] = Reader[R, R](r => r)
def map[R, A, B](r: Reader[R, A], f: A => B): Reader[R, B]
def flatMap[R, A, B](r: Reader[R, A], f: A => Reader[R, B]): Reader[R, B]
// Execution / Interpretation:
def provide[R, A](r: R, reader: Reader[R, A]): A
39. 39
The functional effect of reader
2. Tour of the Effect Zoo
for {
port <- environment[Config].map(_.port)
server <- environment[Config].map(_.server)
retries <- environment[Config].map(_.retries)
} yield (port, server, retries)
Reader[R, A]
40. 40
The functional effect of asynchronous input/output
2. Tour of the Effect Zoo
final case class IO[+A](unsafeRun: (Try[A] => Unit) => Unit)
IO[A]
41. 41
The functional effect of asynchronous input/output
2. Tour of the Effect Zoo
// Core operations:
def sync[A](v: => A): IO[A] = IO(_(Success(v)))
def async[A](r: (Try[A] => Unit) => Unit): IO[A] = IO(r)
def fail(t: Throwable): IO[Nothing] = IO(_(Failure(t)))
def map[A, B](o: IO[A], f: A => B): IO[B]
def flatMap[B, B](o: IO[A], f: A => IO[B]): IO[B]
// Execution / Interpretation:
def unsafeRun[A](io: IO[A], k: Try[A] => Unit): Unit
IO[A]
47. 47
3. Vertical Effect Composition
"Monad transformers allow modular composition of separate
functional effect types into a single functional effect, with the
ability to locally introduce and eliminate effect types."
— John A. De Goes
57. 57
4. Intro to Effect Rotation
sealed trait Either[+A, +B]
case class Left [A](value: A) extends Either[A, Nothing]
case class Right[B](value: B) extends Either[Nothing, B]
Either is the simplest possible failure + success effect
58. 58
4. Intro to Effect Rotation
// Introduction:
def fail[E](e: E): Either[E, Nothing]
// Elimination:
def catchAll[E, A](et: Either[E, A])(f: E => A): Either[Nothing, A]
Either is the simplest possible failure + success effect
Compile-time proof of elimination
59. 59
4. Intro to Effect Rotation
final case class REither[-R, +E, +A](run: R => Either[E, A])
Why stop with error effects?
60. 60
4. Intro to Effect Rotation
// Introduction:
def environment[R]: REither[R, Nothing, R] = REither(r => Right(r))
// Elimination:
def provide[R, E, A](r: R)(re: REither[R, E, A]): REither[Any, E, A] =
REither[Any, E, A](_ => re.run(re))
Introduction and elimination for the reader effect
Compile-time proof of elimination
61. 61
4. Intro to Effect Rotation
final case class REither[-R, +E, +A](run: R => Either[E, A])
Naive encoding shares some overhead with transformers
Dispatch + Boxing Overhead
64. 64
4. Intro to Effect Rotation
sealed trait MTL[-R, +W, S, +E, +A] { self =>
def map[B](f: A => B): MTL[R, W, S, E, B] = ???
def flatMap[..](f: A => MTL[R1, W1, S, E1, B]): MTL[R1, W1, S, E1, B] = ???
// Optimized interpreter for GADT:
def run(r: R, s: S): (List[W], S, Either[E, A]) = ???
}
Possible to eliminate overhead with "free" encodings
65. 65
4. Intro to Effect Rotation
object MTL {
final case class Succeed[S, +A](value: A) extends MTL[Any, Nothing, S, Nothing, A]
final case class Reader [R, S]() extends MTL[R, Nothing, S, Nothing, R]
final case class RunReader[R, +W, S, +E, +A](r: R, mtl: MTL[R, W, S, E, A]) extends MTL[Any, W, S, E, A]
final case class Error [S, +E](error: E) extends MTL[Any, Nothing, S, E, Nothing]
final case class RunError[-R, +W, S, +E, +A](mtl: MTL[R, W, S, E, A]) extends MTL[Any, W, S, Nothing, Either[E, A]]
final case class State [S, +A](f: S => (S, A)) extends MTL[Any, Nothing, S, Nothing, A]
final case class RunState[-R, +W, S, +E, +A](s: S, mtl: MTL[R, W, S, E, A]) extends MTL[R, W, Unit, E, A]
final case class Writer [+W, S](w: W) extends MTL[Any, W, S, Nothing, Unit]
final case class RunWriter[-R, +W, S, +E, +A](mtl: MTL[R, W, S, E, A]) extends MTL[R, Nothing, S, E, (List[W], A)]
final case class FlatMap[R, W, S, E, A, R1 <: R, W1 >: W, E1 >: E, B](first: MTL[R, W, S, E, A], k: A => MTL[R1, W1, S, E1, B]) extends
MTL[R1, W1, S, E1, B]
}
Possible to eliminate overhead with "free" encodings
66. 66
4. Intro to Effect Rotation
Elimination laws for effect rotation
Effect Type Type Elimination Examples
Covariant Nothing Failure, Optionality,
Writer
Contravariant Any Reader
Invariant Unit State
73. 73
5. Practice of Effect Rotation
Option + Either via Error
ZIO[R, Option[E], A]
74. 74
5. Practice of Effect Rotation
trait Ref[A] {
def update(f: A => A): UIO[A]
def modify[B](f: A => (B, A)): UIO[B]
def get: UIO[A]
def set(a: A): UIO[Unit]
}
Reader + Ref / TRef is the key to unlocking other effects!
75. 75
5. Practice of Effect Rotation
Writer via Reader
trait Writer[W] {
def writer: Ref[Vector[W]]
}
def write[W](w: W): ZIO[Writer[W], Nothing, Unit] =
ZIO.accessM[Writer[W]](_.writer.update(_ :+ w).unit)
76. 76
5. Practice of Effect Rotation
State via Reader
trait State[S] {
def state: Ref[S]
}
def modify[S, A](f: S => (S, A)): ZIO[State[S], Nothing, A] =
ZIO.accessM[State[S]](_.state.modify(f))
def update[S, A](f: S => S): ZIO[State[S], Nothing, Unit] = modify(s => (s, ()))
def gets[S]: ZIO[State[S], Nothing, S] = modify(s => (s, s))
77. 77
5. Practice of Effect Rotation
God Monad
type Fx[S, W] = State[S] with Writer[W]
type GodMonad2[+E, W, S, -R <: Fx[S, W], A] =
ZIO[R, Option[E], A]
78. 78
5. Practice of Effect Rotation
Effect rotation delivers resource / concurrent safety!
Monad Transformers Effect Rotation
... ... ...
Concurrent-Safe State ❌ ✅
Concurrrent Safe Writer ❌ ✅
Resource-Safe State ❌ ✅
Resource-Safe Writer ❌ ✅