SlideShare a Scribd company logo
Tagless Final Encoding
Algebras and Interpreters
and also Programs
an introduction, through the work of Gabriel Volpe
Algebras
Tagless Final
Encoding
@philip_schwarz
slides by http://fpilluminated.com/
This slide deck is a quick, introductory look, at Tagless Final, as explained (in rather more depth
than is possible or appropriate here) by Gabriel in his great book: Practical FP in Scala, a Hands-
on Approach.
In the first six slides, we are going to see Gabriel introduce the key elements of the technique.
Tagless final is all about algebras and interpreters. Yet,
something is missing when it comes to writing applications…
Tagless final is a great technique used to
structure purely functional applications.
Yes, as you’ll see, to the two official pillars of Tagless Final, i.e. algebras and interpreters, Gabriel
adds a third one: programs.
Algebras
Tagless Final
Encoding
@philip_schwarz
Algebras
An algebra describes a new language (DSL) within a host language, in this case, Scala.
This is a tagless final encoded algebra; tagless algebra, or algebra for short: a simple interface that
abstracts over the effect type using a type constructor F[_].
Do not confuse algebras with typeclasses, which in Scala, happen to share the same encoding.
The difference is that typeclasses should have coherent instances, whereas tagless algebras could have
many implementations, or more commonly called interpreters.
…
Overall, tagless algebras seem a perfect fit for encoding business concepts. For example, an algebra
responsible for managing items could be encoded as follows.
Nothing new, right? This tagless final encoded algebra is merely an interface that abstracts over the effect
type. Notice that neither the algebra nor its functions have any typeclass constraint.
If you find yourself needing to add a typeclass constraint, such as Monad, to your algebra, what you probably
need is a program.
The reason being that typeclass constraints define capabilities, which belong in programs and interpreters.
Algebras should remain completely abstract.
trait Items[F[_]] {
def getAll: F[List[Item]]
def add(item: Item): F[Unit]
}
trait Counter[F[_]] {
def increment: F[Unit]
def get: F[Int]
}
Tagless algebras should not have typeclass constraints
Tips
Interpreters
We would normally have two interpreters per algebra: one for testing and one for doing real things. For
instance, we could have two different implementations of our Counter.
A default interpreter using Redis.
And a test interpreter using an in-memory data structure.
Interpreters help us encapsulate state and allow separation of concerns: the interface knows nothing about
the implementation details. Moreover, interpreters can be written either using a concrete datatype such as
IO or going polymorphic all the way, as we did in this case.
object Counter {
@newtype case class RedisKey(value: String)
def make[F[_]: Functor](
key: RedisKey,
cmd: RedisCommands[F, String, Int]
): Counter[F] =
new Counter[F] {
def increment: F[Unit] =
cmd.increment(key.value).void
def get: F[Int] =
cmd.get(key.value).map(_.getOrElse(0))
}
}
def testCounter[F[_]](
ref: Ref[F, Int]
): Counter[F] = new Counter[F] {
def increment: F[Unit] = ref.update(_ + 1)
def get: F[Int] = ref.get
}
We are currently working our way through slides containing excerpts from Chapter 2: Tagless Final Encoding.
The next slide is an exception in that it contains an excerpt from Chapter1: Best Practices, which has already
introduced (in a less formal way), the concept of an interpreter for the Counter trait (without yet referring to
the latter as an algebra).
In-memory counter
Let’s say we need an in-memory counter that needs to be accessed and modified by other components. Here
is what our interface could look like.
It has a higher-kinded type F[_], representing an abstract effect, which most of the time ends up being IO,
but it could really be any other concrete type that fits the shape.
Next, we need to define an interpreter in the companion object of our interface, in this case using a Ref. We
will talk more about it in the next section.
…
Moving on, it’s worth highlighting that other programs will interact with this counter solely via its interface. E.g.
// prints out 0,1,6 when executed
def program(c: Counter[IO]): IO[Unit] =
for {
_ <- c.get.flatMap(IO.println)
_ <- c.increment
_ <- c.get.flatMap(IO.println)
_ <- c.increment.replicateA(5).void
_ <- c.get.flatMap(IO.println)
} yield ()
In the next chapter, we will discuss whether it is best to pass the dependency implicitly or explicitly.
object Counter {
def make[F[_]: Functor: Ref.Make]: F[Counter[F]] =
Ref.of[F, Int](0).map { ref =>
new Counter[F] {
def increment: F[Unit] = ref.update(_ + 1)
def get: F[Int] = ref.get
}
}
}
trait Counter[F[_]] {
def increment: F[Unit]
def get: F[Int]
}
import cats.Functor
import cats.effect.kernel.Ref
import cats.syntax.functor._
Programs
Tagless final is all about algebras and interpreters. Yet, something is missing when it comes to writing applications: we
need to use these algebras to describe business logic, and this logic belongs in what I like to call programs.
Although it is not an official name – and it is not mentioned in the original tagless final paper – it is how we will be
referring to such interfaces in this book.
Say we need to increase a counter every time there is a new item added. We could encode it as follows.
Observe the characteristics of this program. It is pure business logic, and it holds no state at all, which in any case,
must be encapsulated in the interpreters. Notice the typeclass constraints as well; it is a good practice to have them
in programs instead of tagless algebras.
…
Moreover, we can discuss typeclass constraints. In this case, we only need Apply to use *> (alias for productR).
However, it would also work with Applicative or Monad. The rule of thumb is to limit ourselves to adopt the least
powerful typeclass that gets the job done.
It is worth mentioning that Apply itself doesn’t specify the semantics of composition solely with this constraint, *>
might combine its arguments sequentially or parallelly, depending on the underlying typeclass instance. To ensure
our composition is sequential, we could use FlatMap instead of Apply.
class ItemsCounter[F[_]: Apply](
counter: Counter[F],
items: Items[F]
){
def addItem(item: Item): F[Unit] =
items.add(item) *>
counter.increment
}
Programs can make use of algebras and other programs
Notes
When adding a typeclass constraint, remember about the principle of least power
Tips
Other kinds of programs might be directly encoded as functions.
Furthermore, we could have programs composed of other programs.
Whether we encode programs in one way or another, they should describe pure business logic and nothing else.
The question is: what is pure business logic? We could try and define a set of rules to abide by. It is allowed to:
• Combine pure computations in terms of tagless algebras and programs.
– Only doing what our effect constraints allows us to do.
• Perform logging (or console stuff) only via a tagless algebra.
– In Chapter 8, we will see how to ignore logging or console stuff in tests, which are most of the time irrelevant in
such context.
You can use this as a reference. However, the answer should come up as a collective agreement within your team.
def program[F[_]: Console: Monad]: F[Unit] =
for {
_ <- Console[F].println("Enter your name: ")
n <- Console[F].readLine
_ <- Console[F].println(s"Hello $n!")
} yield ()
class MasterMind[F[_]: Console: Monad](
itemsCounter: ItemsCounter[F],
counter: Counter[F]
){
def logic(item: Item): F[Unit] =
for {
_ <- itemsCounter.addItem(item)
c <- counter.get
_ <- Console[F].println(s"Number of items: $c")
} yield ()
}
def program(counter: Counter[IO]): IO[Unit] =
for {
_ <- display(counter)
_ <- counter.increment
_ <- display(counter)
_ <- repeat(5){ counter.increment }
_ <- display(counter)
} yield ()
def display(counter: Counter[IO]): IO[Unit] =
counter.get.flatMap(IO.println)
def repeat(n: Int)(action: IO[Unit]): IO[Unit] =
action.replicateA(n).void
def program(c: Counter[IO]): IO[Unit] =
for {
_ <- c.get.flatMap(IO.println)
_ <- c.increment
_ <- c.get.flatMap(IO.println)
_ <- c.increment.replicateA(5).void
_ <- c.get.flatMap(IO.println)
} yield ()
REFACTOR
Let’s refactor a little bit the first program that we came across.
On the next slide, we are going to take that program and wrap it in a tiny application that can be executed.
We are also going to use a little bit of UML, to show how the program uses an algebra (i.e. an interface) implemented by an interpreter.
To do this, we are going to slightly abuse UML, along the lines described by Martin Fowler in https://martinfowler.com/bliki/BallAndSocket.html.
Program
Algebra
Interface Algebra is used (required) by Program.
Interface Algebra is realized (implemented) by Interpreter.
Interpreter
Algebra
Program Interpreter
Algebra
Interface Algebra, which is realized (implemented)
by Interpreter, is used (required) by Program.
Algebra
ball
Algebra interface.
In a further twist, I’ll also be putting Algebra inside the ball.
socket
mated socket and ball
valid UML notation
invalid
UML
notation
@philip_schwarz
import cats.effect.IO
import cats.effect.IOApp.Simple
object Application extends Simple {
// prints out 0, 1, 6 when executed
override def run: IO[Unit] =
Counter.make[IO].flatMap(program(_))
private def program(counter: Counter[IO]): IO[Unit] =
for {
_ <- display(counter)
_ <- counter.increment
_ <- display(counter)
_ <- repeat(5){ counter.increment }
_ <- display(counter)
} yield ()
private def display(counter: Counter[IO]): IO[Unit] =
counter.get.flatMap(IO.println)
private def repeat(n: Int)(action: IO[Unit]): IO[Unit] =
action.replicateA(n).void
}
trait Counter[F[_]] {
def increment: F[Unit]
def get: F[Int]
}
Algebra
Program
object Counter {
def make[F[_]: Functor: Ref.Make]: F[Counter[F]] =
Ref.of[F, Int](0).map { ref =>
new Counter[F] {
def increment: F[Unit] =
ref.update(_ + 1)
def get: F[Int] =
ref.get
}
}
}
Interpreter
Next, we take the mastermind program that we saw earlier, and
use it in a tiny application that tests it a bit.
Because we are going to need it in the next slide, here is a much
pared down version of the Item referenced by the program.
import io.estatico.newtype.macros.newtype
import java.util.UUID
object item {
@newtype case class ItemId(value: UUID)
@newtype case class ItemName(value: String)
@newtype case class ItemDescription(value: String)
case class Item(uuid: ItemId, name: ItemName, description: ItemDescription)
}
class ItemsCounter[F[_]: Apply](
counter: Counter[F],
items: Items[F]
){
def addItem(item: Item): F[Unit] =
items.add(item) *>
counter.increment
}
class MasterMind[F[_]: Console: Monad](
itemsCounter: ItemsCounter[F],
counter: Counter[F]
){
def logic(item: Item): F[Unit] =
for {
_ <- itemsCounter.addItem(item)
c <- counter.get
_ <- Console[F].println(s"Number of items: $c")
} yield ()
}
trait Counter[F[_]] {
def increment: F[Unit]
def get: F[Int]
}
trait Items[F[_]] {
def getAll: F[List[Item]]
def add(item: Item): F[Unit]
}
object TestCounter {
def make[F[_]: Functor: Ref.Make]: F[Counter[F]] =
Ref.of[F, Int[(0).map { ref =>
new Counter[F] {
def increment: F[Unit] =
ref.update(_ + 1)
def get: F[Int] =
ref.get
}
}
object TestItems {
def make[F[_]: Functor : Ref.Make]: F[Items[F]] =
Ref.of[F, Map[ItemId, Item]](Map.empty).map { ref =>
new Items[F] {
def getAll: F[List[Item]] =
ref.get.map(_.values.toList)
def add(item: Item): F[Unit] =
ref.update(_ + (item.uuid -> item))
}
}
}
import cats.effect.IO
import cats.effect.IOApp.Simple
import item.{Item, ItemDescription, ItemId, ItemName}
import java.util.UUID
object TestMasterMindProgram extends Simple {
val item = Item(
ItemId(UUID.fromString("0c69d914-6ff6-11ee-b962-0242ac120002")),
ItemName("Practical FP in Scala"),
ItemDescription("A great book")
)
override def run: IO[Unit] = {
for {
counter <- TestCounter.make[IO]
items <- TestItems.make[IO]
itemsCounter = new ItemsCounter[IO](counter, items)
masterMind = new MasterMind(itemsCounter, counter)
itemsBefore <- items.getAll
countBefore <- counter.get
_ = assert(itemsBefore.isEmpty)
_ = assert(countBefore == 0)
_ <- masterMind.logic(item)
itemsAfter <- items.getAll
countAfter <- counter.get
_ = assert(itemsAfter.sameElements(List(item)))
_ = assert(countAfter == 1)
} yield ()
}
}
Algebra
Interpreter
Program
Algebra
Interpreter
Program
Program
Of course this was just a quick introduction to the Tagless Final technique.
See the book for much more depth, and many other important aspects of using the technique.
The next slide contains just a taster.
Some might question the decision to invest in this technique for a business application, claiming it entails great complexity.
This is a fair concern but let’s ask ourselves, what’s the alternative? Using IO directly in the entire application? By all means,
this could work, but at what cost? At the very least, we would be giving up on parametricity† and the principle of least power.
There is a huge mix of concerns. How can we possibly
reason about this function? How can we even test it? We
got ourselves into a very uncomfortable situation.
Now let’s compare it against the abstract equivalent of
it. Instead of performing side-effects, we have now
typeclass constraints and capabilities.
Teams making use of this technique will immediately understand that all we can do in the body of the constrained function is to compose
Counter, Log, and Time actions sequentially as well as to use any property made available by the Monad constraint. It is true, however, that
the Scala compiler does not enforce it so this is up to the discipline of the team.
Since Scala is a hybrid language, the only thing stopping us from running wild side-effects in this function is self-discipline and peer reviews.
However, good practices are required in any team for multiple purposes, so I would argue it is not necessarily a bad thing, as we can do the same
thing in programs encoded directly in IO.
† https://en.wikipedia.org/wiki/Parametricity
That’s all. I hope you found it useful.

More Related Content

What's hot

Functional and Event Driven - another approach to domain modeling
Functional and Event Driven - another approach to domain modelingFunctional and Event Driven - another approach to domain modeling
Functional and Event Driven - another approach to domain modeling
Debasish Ghosh
 
Oop
OopOop
Point free or die - tacit programming in Haskell and beyond
Point free or die - tacit programming in Haskell and beyondPoint free or die - tacit programming in Haskell and beyond
Point free or die - tacit programming in Haskell and beyond
Philip Schwarz
 
The Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and FoldThe Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and Fold
Philip Schwarz
 
An introduction to Apache Hadoop Hive
An introduction to Apache Hadoop HiveAn introduction to Apache Hadoop Hive
An introduction to Apache Hadoop Hive
Mike Frampton
 
‘go-to’ general-purpose sequential collections - from Java To Scala
‘go-to’ general-purpose sequential collections -from Java To Scala‘go-to’ general-purpose sequential collections -from Java To Scala
‘go-to’ general-purpose sequential collections - from Java To Scala
Philip Schwarz
 
Adding measures to Calcite SQL
Adding measures to Calcite SQLAdding measures to Calcite SQL
Adding measures to Calcite SQL
Julian Hyde
 
Capabilities for Resources and Effects
Capabilities for Resources and EffectsCapabilities for Resources and Effects
Capabilities for Resources and Effects
Martin Odersky
 
Hibernate Basic Concepts - Presentation
Hibernate Basic Concepts - PresentationHibernate Basic Concepts - Presentation
Hibernate Basic Concepts - Presentation
Khoa Nguyen
 
scalar.pdf
scalar.pdfscalar.pdf
scalar.pdf
Martin Odersky
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 
Javascript Prototypal Inheritance - Big Picture
Javascript Prototypal Inheritance - Big PictureJavascript Prototypal Inheritance - Big Picture
Javascript Prototypal Inheritance - Big Picture
Manish Jangir
 
Applicative Functor
Applicative FunctorApplicative Functor
Applicative Functor
Philip Schwarz
 
GraphQL
GraphQLGraphQL
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHP
Ramasubbu .P
 
(알도개) GraalVM – 자바를 넘어선 새로운 시작의 서막
(알도개) GraalVM – 자바를 넘어선 새로운 시작의 서막(알도개) GraalVM – 자바를 넘어선 새로운 시작의 서막
(알도개) GraalVM – 자바를 넘어선 새로운 시작의 서막
Jay Park
 
The aggregate function - from sequential and parallel folds to parallel aggre...
The aggregate function - from sequential and parallel folds to parallel aggre...The aggregate function - from sequential and parallel folds to parallel aggre...
The aggregate function - from sequential and parallel folds to parallel aggre...
Philip Schwarz
 
Fusing Transformations of Strict Scala Collections with Views
Fusing Transformations of Strict Scala Collections with ViewsFusing Transformations of Strict Scala Collections with Views
Fusing Transformations of Strict Scala Collections with Views
Philip Schwarz
 
React render props
React render propsReact render props
React render props
Saikat Samanta
 

What's hot (20)

Functional and Event Driven - another approach to domain modeling
Functional and Event Driven - another approach to domain modelingFunctional and Event Driven - another approach to domain modeling
Functional and Event Driven - another approach to domain modeling
 
Oop
OopOop
Oop
 
Point free or die - tacit programming in Haskell and beyond
Point free or die - tacit programming in Haskell and beyondPoint free or die - tacit programming in Haskell and beyond
Point free or die - tacit programming in Haskell and beyond
 
The Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and FoldThe Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and Fold
 
An introduction to Apache Hadoop Hive
An introduction to Apache Hadoop HiveAn introduction to Apache Hadoop Hive
An introduction to Apache Hadoop Hive
 
‘go-to’ general-purpose sequential collections - from Java To Scala
‘go-to’ general-purpose sequential collections -from Java To Scala‘go-to’ general-purpose sequential collections -from Java To Scala
‘go-to’ general-purpose sequential collections - from Java To Scala
 
Adding measures to Calcite SQL
Adding measures to Calcite SQLAdding measures to Calcite SQL
Adding measures to Calcite SQL
 
Capabilities for Resources and Effects
Capabilities for Resources and EffectsCapabilities for Resources and Effects
Capabilities for Resources and Effects
 
Hibernate Basic Concepts - Presentation
Hibernate Basic Concepts - PresentationHibernate Basic Concepts - Presentation
Hibernate Basic Concepts - Presentation
 
JavaScript Inheritance
JavaScript InheritanceJavaScript Inheritance
JavaScript Inheritance
 
scalar.pdf
scalar.pdfscalar.pdf
scalar.pdf
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Javascript Prototypal Inheritance - Big Picture
Javascript Prototypal Inheritance - Big PictureJavascript Prototypal Inheritance - Big Picture
Javascript Prototypal Inheritance - Big Picture
 
Applicative Functor
Applicative FunctorApplicative Functor
Applicative Functor
 
GraphQL
GraphQLGraphQL
GraphQL
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHP
 
(알도개) GraalVM – 자바를 넘어선 새로운 시작의 서막
(알도개) GraalVM – 자바를 넘어선 새로운 시작의 서막(알도개) GraalVM – 자바를 넘어선 새로운 시작의 서막
(알도개) GraalVM – 자바를 넘어선 새로운 시작의 서막
 
The aggregate function - from sequential and parallel folds to parallel aggre...
The aggregate function - from sequential and parallel folds to parallel aggre...The aggregate function - from sequential and parallel folds to parallel aggre...
The aggregate function - from sequential and parallel folds to parallel aggre...
 
Fusing Transformations of Strict Scala Collections with Views
Fusing Transformations of Strict Scala Collections with ViewsFusing Transformations of Strict Scala Collections with Views
Fusing Transformations of Strict Scala Collections with Views
 
React render props
React render propsReact render props
React render props
 

Similar to Tagless Final Encoding - Algebras and Interpreters and also Programs

Java modular extension for operator overloading
Java modular extension for operator overloadingJava modular extension for operator overloading
Java modular extension for operator overloading
ijpla
 
Functional Effects - Part 1
Functional Effects - Part 1Functional Effects - Part 1
Functional Effects - Part 1
Philip Schwarz
 
Function
FunctionFunction
Function
MuhammadBakri13
 
Chapter 1.ppt
Chapter 1.pptChapter 1.ppt
Chapter 1.ppt
ethiouniverse
 
Presentation 2.pptx
Presentation 2.pptxPresentation 2.pptx
Presentation 2.pptx
ziyadaslanbey
 
Algorithm and c language
Algorithm and c languageAlgorithm and c language
Algorithm and c language
kamalbeydoun
 
Book management system
Book management systemBook management system
Book management system
SHARDA SHARAN
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An Overview
Indrajit Das
 
Tutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng verTutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng ver
Qrembiezs Intruder
 
Java 8-revealed
Java 8-revealedJava 8-revealed
Java 8-revealed
Hamed Hatami
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
Asaye Dilbo
 
Presentation 2 (1).pdf
Presentation 2 (1).pdfPresentation 2 (1).pdf
Presentation 2 (1).pdf
ziyadaslanbey
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Modeling Aspects with AP&P Components
Modeling Aspects with AP&P ComponentsModeling Aspects with AP&P Components
Modeling Aspects with AP&P Components
mukhtarhudaya
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
AMAN ANAND
 
C functions
C functionsC functions
C programming languag for cse students
C programming languag for cse studentsC programming languag for cse students
C programming languag for cse students
Abdur Rahim
 
Mastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsMastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_arguments
Ruth Marvin
 

Similar to Tagless Final Encoding - Algebras and Interpreters and also Programs (20)

Java modular extension for operator overloading
Java modular extension for operator overloadingJava modular extension for operator overloading
Java modular extension for operator overloading
 
Functional Effects - Part 1
Functional Effects - Part 1Functional Effects - Part 1
Functional Effects - Part 1
 
Function
FunctionFunction
Function
 
Chapter 1.ppt
Chapter 1.pptChapter 1.ppt
Chapter 1.ppt
 
Presentation 2.pptx
Presentation 2.pptxPresentation 2.pptx
Presentation 2.pptx
 
Algorithm and c language
Algorithm and c languageAlgorithm and c language
Algorithm and c language
 
Book management system
Book management systemBook management system
Book management system
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An Overview
 
Tutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng verTutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng ver
 
Java 8-revealed
Java 8-revealedJava 8-revealed
Java 8-revealed
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Function
FunctionFunction
Function
 
Presentation 2 (1).pdf
Presentation 2 (1).pdfPresentation 2 (1).pdf
Presentation 2 (1).pdf
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Bcsl 031 solve assignment
 
Modeling Aspects with AP&P Components
Modeling Aspects with AP&P ComponentsModeling Aspects with AP&P Components
Modeling Aspects with AP&P Components
 
ACM init()- Day 4
ACM init()- Day 4ACM init()- Day 4
ACM init()- Day 4
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
C functions
C functionsC functions
C functions
 
C programming languag for cse students
C programming languag for cse studentsC programming languag for cse students
C programming languag for cse students
 
Mastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsMastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_arguments
 

More from Philip Schwarz

A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Philip Schwarz
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
Philip Schwarz
 
Folding Cheat Sheet #3 - third in a series
Folding Cheat Sheet #3 - third in a seriesFolding Cheat Sheet #3 - third in a series
Folding Cheat Sheet #3 - third in a series
Philip Schwarz
 
Folding Cheat Sheet #2 - second in a series
Folding Cheat Sheet #2 - second in a seriesFolding Cheat Sheet #2 - second in a series
Folding Cheat Sheet #2 - second in a series
Philip Schwarz
 
Folding Cheat Sheet #1 - first in a series
Folding Cheat Sheet #1 - first in a seriesFolding Cheat Sheet #1 - first in a series
Folding Cheat Sheet #1 - first in a series
Philip Schwarz
 
Scala Left Fold Parallelisation - Three Approaches
Scala Left Fold Parallelisation- Three ApproachesScala Left Fold Parallelisation- Three Approaches
Scala Left Fold Parallelisation - Three Approaches
Philip Schwarz
 
A sighting of traverse_ function in Practical FP in Scala
A sighting of traverse_ function in Practical FP in ScalaA sighting of traverse_ function in Practical FP in Scala
A sighting of traverse_ function in Practical FP in Scala
Philip Schwarz
 
A sighting of traverseFilter and foldMap in Practical FP in Scala
A sighting of traverseFilter and foldMap in Practical FP in ScalaA sighting of traverseFilter and foldMap in Practical FP in Scala
A sighting of traverseFilter and foldMap in Practical FP in Scala
Philip Schwarz
 
A sighting of sequence function in Practical FP in Scala
A sighting of sequence function in Practical FP in ScalaA sighting of sequence function in Practical FP in Scala
A sighting of sequence function in Practical FP in Scala
Philip Schwarz
 
N-Queens Combinatorial Puzzle meets Cats
N-Queens Combinatorial Puzzle meets CatsN-Queens Combinatorial Puzzle meets Cats
N-Queens Combinatorial Puzzle meets Cats
Philip Schwarz
 
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
Philip Schwarz
 
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
Nat, List and Option Monoids -from scratch -Combining and Folding -an exampleNat, List and Option Monoids -from scratch -Combining and Folding -an example
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
Philip Schwarz
 
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
Nat, List and Option Monoids -from scratch -Combining and Folding -an exampleNat, List and Option Monoids -from scratch -Combining and Folding -an example
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
Philip Schwarz
 
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
Philip Schwarz
 
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
Philip Schwarz
 
Jordan Peterson - The pursuit of meaning and related ethical axioms
Jordan Peterson - The pursuit of meaning and related ethical axiomsJordan Peterson - The pursuit of meaning and related ethical axioms
Jordan Peterson - The pursuit of meaning and related ethical axioms
Philip Schwarz
 
Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...
Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...
Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...
Philip Schwarz
 
Defining filter using (a) recursion (b) folding with S, B and I combinators (...
Defining filter using (a) recursion (b) folding with S, B and I combinators (...Defining filter using (a) recursion (b) folding with S, B and I combinators (...
Defining filter using (a) recursion (b) folding with S, B and I combinators (...
Philip Schwarz
 
The Sieve of Eratosthenes - Part 1 - with minor corrections
The Sieve of Eratosthenes - Part 1 - with minor correctionsThe Sieve of Eratosthenes - Part 1 - with minor corrections
The Sieve of Eratosthenes - Part 1 - with minor corrections
Philip Schwarz
 

More from Philip Schwarz (20)

A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Folding Cheat Sheet #3 - third in a series
Folding Cheat Sheet #3 - third in a seriesFolding Cheat Sheet #3 - third in a series
Folding Cheat Sheet #3 - third in a series
 
Folding Cheat Sheet #2 - second in a series
Folding Cheat Sheet #2 - second in a seriesFolding Cheat Sheet #2 - second in a series
Folding Cheat Sheet #2 - second in a series
 
Folding Cheat Sheet #1 - first in a series
Folding Cheat Sheet #1 - first in a seriesFolding Cheat Sheet #1 - first in a series
Folding Cheat Sheet #1 - first in a series
 
Scala Left Fold Parallelisation - Three Approaches
Scala Left Fold Parallelisation- Three ApproachesScala Left Fold Parallelisation- Three Approaches
Scala Left Fold Parallelisation - Three Approaches
 
A sighting of traverse_ function in Practical FP in Scala
A sighting of traverse_ function in Practical FP in ScalaA sighting of traverse_ function in Practical FP in Scala
A sighting of traverse_ function in Practical FP in Scala
 
A sighting of traverseFilter and foldMap in Practical FP in Scala
A sighting of traverseFilter and foldMap in Practical FP in ScalaA sighting of traverseFilter and foldMap in Practical FP in Scala
A sighting of traverseFilter and foldMap in Practical FP in Scala
 
A sighting of sequence function in Practical FP in Scala
A sighting of sequence function in Practical FP in ScalaA sighting of sequence function in Practical FP in Scala
A sighting of sequence function in Practical FP in Scala
 
N-Queens Combinatorial Puzzle meets Cats
N-Queens Combinatorial Puzzle meets CatsN-Queens Combinatorial Puzzle meets Cats
N-Queens Combinatorial Puzzle meets Cats
 
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
 
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
Nat, List and Option Monoids -from scratch -Combining and Folding -an exampleNat, List and Option Monoids -from scratch -Combining and Folding -an example
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
 
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
Nat, List and Option Monoids -from scratch -Combining and Folding -an exampleNat, List and Option Monoids -from scratch -Combining and Folding -an example
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
 
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
 
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
 
Jordan Peterson - The pursuit of meaning and related ethical axioms
Jordan Peterson - The pursuit of meaning and related ethical axiomsJordan Peterson - The pursuit of meaning and related ethical axioms
Jordan Peterson - The pursuit of meaning and related ethical axioms
 
Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...
Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...
Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...
 
Defining filter using (a) recursion (b) folding with S, B and I combinators (...
Defining filter using (a) recursion (b) folding with S, B and I combinators (...Defining filter using (a) recursion (b) folding with S, B and I combinators (...
Defining filter using (a) recursion (b) folding with S, B and I combinators (...
 
The Sieve of Eratosthenes - Part 1 - with minor corrections
The Sieve of Eratosthenes - Part 1 - with minor correctionsThe Sieve of Eratosthenes - Part 1 - with minor corrections
The Sieve of Eratosthenes - Part 1 - with minor corrections
 

Recently uploaded

Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Jay Das
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
Srikant77
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 

Recently uploaded (20)

Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 

Tagless Final Encoding - Algebras and Interpreters and also Programs

  • 1. Tagless Final Encoding Algebras and Interpreters and also Programs an introduction, through the work of Gabriel Volpe Algebras Tagless Final Encoding @philip_schwarz slides by http://fpilluminated.com/
  • 2. This slide deck is a quick, introductory look, at Tagless Final, as explained (in rather more depth than is possible or appropriate here) by Gabriel in his great book: Practical FP in Scala, a Hands- on Approach. In the first six slides, we are going to see Gabriel introduce the key elements of the technique. Tagless final is all about algebras and interpreters. Yet, something is missing when it comes to writing applications… Tagless final is a great technique used to structure purely functional applications. Yes, as you’ll see, to the two official pillars of Tagless Final, i.e. algebras and interpreters, Gabriel adds a third one: programs. Algebras Tagless Final Encoding @philip_schwarz
  • 3. Algebras An algebra describes a new language (DSL) within a host language, in this case, Scala. This is a tagless final encoded algebra; tagless algebra, or algebra for short: a simple interface that abstracts over the effect type using a type constructor F[_]. Do not confuse algebras with typeclasses, which in Scala, happen to share the same encoding. The difference is that typeclasses should have coherent instances, whereas tagless algebras could have many implementations, or more commonly called interpreters. … Overall, tagless algebras seem a perfect fit for encoding business concepts. For example, an algebra responsible for managing items could be encoded as follows. Nothing new, right? This tagless final encoded algebra is merely an interface that abstracts over the effect type. Notice that neither the algebra nor its functions have any typeclass constraint. If you find yourself needing to add a typeclass constraint, such as Monad, to your algebra, what you probably need is a program. The reason being that typeclass constraints define capabilities, which belong in programs and interpreters. Algebras should remain completely abstract. trait Items[F[_]] { def getAll: F[List[Item]] def add(item: Item): F[Unit] } trait Counter[F[_]] { def increment: F[Unit] def get: F[Int] } Tagless algebras should not have typeclass constraints Tips
  • 4. Interpreters We would normally have two interpreters per algebra: one for testing and one for doing real things. For instance, we could have two different implementations of our Counter. A default interpreter using Redis. And a test interpreter using an in-memory data structure. Interpreters help us encapsulate state and allow separation of concerns: the interface knows nothing about the implementation details. Moreover, interpreters can be written either using a concrete datatype such as IO or going polymorphic all the way, as we did in this case. object Counter { @newtype case class RedisKey(value: String) def make[F[_]: Functor]( key: RedisKey, cmd: RedisCommands[F, String, Int] ): Counter[F] = new Counter[F] { def increment: F[Unit] = cmd.increment(key.value).void def get: F[Int] = cmd.get(key.value).map(_.getOrElse(0)) } } def testCounter[F[_]]( ref: Ref[F, Int] ): Counter[F] = new Counter[F] { def increment: F[Unit] = ref.update(_ + 1) def get: F[Int] = ref.get }
  • 5. We are currently working our way through slides containing excerpts from Chapter 2: Tagless Final Encoding. The next slide is an exception in that it contains an excerpt from Chapter1: Best Practices, which has already introduced (in a less formal way), the concept of an interpreter for the Counter trait (without yet referring to the latter as an algebra).
  • 6. In-memory counter Let’s say we need an in-memory counter that needs to be accessed and modified by other components. Here is what our interface could look like. It has a higher-kinded type F[_], representing an abstract effect, which most of the time ends up being IO, but it could really be any other concrete type that fits the shape. Next, we need to define an interpreter in the companion object of our interface, in this case using a Ref. We will talk more about it in the next section. … Moving on, it’s worth highlighting that other programs will interact with this counter solely via its interface. E.g. // prints out 0,1,6 when executed def program(c: Counter[IO]): IO[Unit] = for { _ <- c.get.flatMap(IO.println) _ <- c.increment _ <- c.get.flatMap(IO.println) _ <- c.increment.replicateA(5).void _ <- c.get.flatMap(IO.println) } yield () In the next chapter, we will discuss whether it is best to pass the dependency implicitly or explicitly. object Counter { def make[F[_]: Functor: Ref.Make]: F[Counter[F]] = Ref.of[F, Int](0).map { ref => new Counter[F] { def increment: F[Unit] = ref.update(_ + 1) def get: F[Int] = ref.get } } } trait Counter[F[_]] { def increment: F[Unit] def get: F[Int] } import cats.Functor import cats.effect.kernel.Ref import cats.syntax.functor._
  • 7. Programs Tagless final is all about algebras and interpreters. Yet, something is missing when it comes to writing applications: we need to use these algebras to describe business logic, and this logic belongs in what I like to call programs. Although it is not an official name – and it is not mentioned in the original tagless final paper – it is how we will be referring to such interfaces in this book. Say we need to increase a counter every time there is a new item added. We could encode it as follows. Observe the characteristics of this program. It is pure business logic, and it holds no state at all, which in any case, must be encapsulated in the interpreters. Notice the typeclass constraints as well; it is a good practice to have them in programs instead of tagless algebras. … Moreover, we can discuss typeclass constraints. In this case, we only need Apply to use *> (alias for productR). However, it would also work with Applicative or Monad. The rule of thumb is to limit ourselves to adopt the least powerful typeclass that gets the job done. It is worth mentioning that Apply itself doesn’t specify the semantics of composition solely with this constraint, *> might combine its arguments sequentially or parallelly, depending on the underlying typeclass instance. To ensure our composition is sequential, we could use FlatMap instead of Apply. class ItemsCounter[F[_]: Apply]( counter: Counter[F], items: Items[F] ){ def addItem(item: Item): F[Unit] = items.add(item) *> counter.increment } Programs can make use of algebras and other programs Notes When adding a typeclass constraint, remember about the principle of least power Tips
  • 8. Other kinds of programs might be directly encoded as functions. Furthermore, we could have programs composed of other programs. Whether we encode programs in one way or another, they should describe pure business logic and nothing else. The question is: what is pure business logic? We could try and define a set of rules to abide by. It is allowed to: • Combine pure computations in terms of tagless algebras and programs. – Only doing what our effect constraints allows us to do. • Perform logging (or console stuff) only via a tagless algebra. – In Chapter 8, we will see how to ignore logging or console stuff in tests, which are most of the time irrelevant in such context. You can use this as a reference. However, the answer should come up as a collective agreement within your team. def program[F[_]: Console: Monad]: F[Unit] = for { _ <- Console[F].println("Enter your name: ") n <- Console[F].readLine _ <- Console[F].println(s"Hello $n!") } yield () class MasterMind[F[_]: Console: Monad]( itemsCounter: ItemsCounter[F], counter: Counter[F] ){ def logic(item: Item): F[Unit] = for { _ <- itemsCounter.addItem(item) c <- counter.get _ <- Console[F].println(s"Number of items: $c") } yield () }
  • 9. def program(counter: Counter[IO]): IO[Unit] = for { _ <- display(counter) _ <- counter.increment _ <- display(counter) _ <- repeat(5){ counter.increment } _ <- display(counter) } yield () def display(counter: Counter[IO]): IO[Unit] = counter.get.flatMap(IO.println) def repeat(n: Int)(action: IO[Unit]): IO[Unit] = action.replicateA(n).void def program(c: Counter[IO]): IO[Unit] = for { _ <- c.get.flatMap(IO.println) _ <- c.increment _ <- c.get.flatMap(IO.println) _ <- c.increment.replicateA(5).void _ <- c.get.flatMap(IO.println) } yield () REFACTOR Let’s refactor a little bit the first program that we came across.
  • 10. On the next slide, we are going to take that program and wrap it in a tiny application that can be executed. We are also going to use a little bit of UML, to show how the program uses an algebra (i.e. an interface) implemented by an interpreter. To do this, we are going to slightly abuse UML, along the lines described by Martin Fowler in https://martinfowler.com/bliki/BallAndSocket.html. Program Algebra Interface Algebra is used (required) by Program. Interface Algebra is realized (implemented) by Interpreter. Interpreter Algebra Program Interpreter Algebra Interface Algebra, which is realized (implemented) by Interpreter, is used (required) by Program. Algebra ball Algebra interface. In a further twist, I’ll also be putting Algebra inside the ball. socket mated socket and ball valid UML notation invalid UML notation @philip_schwarz
  • 11. import cats.effect.IO import cats.effect.IOApp.Simple object Application extends Simple { // prints out 0, 1, 6 when executed override def run: IO[Unit] = Counter.make[IO].flatMap(program(_)) private def program(counter: Counter[IO]): IO[Unit] = for { _ <- display(counter) _ <- counter.increment _ <- display(counter) _ <- repeat(5){ counter.increment } _ <- display(counter) } yield () private def display(counter: Counter[IO]): IO[Unit] = counter.get.flatMap(IO.println) private def repeat(n: Int)(action: IO[Unit]): IO[Unit] = action.replicateA(n).void } trait Counter[F[_]] { def increment: F[Unit] def get: F[Int] } Algebra Program object Counter { def make[F[_]: Functor: Ref.Make]: F[Counter[F]] = Ref.of[F, Int](0).map { ref => new Counter[F] { def increment: F[Unit] = ref.update(_ + 1) def get: F[Int] = ref.get } } } Interpreter
  • 12. Next, we take the mastermind program that we saw earlier, and use it in a tiny application that tests it a bit. Because we are going to need it in the next slide, here is a much pared down version of the Item referenced by the program. import io.estatico.newtype.macros.newtype import java.util.UUID object item { @newtype case class ItemId(value: UUID) @newtype case class ItemName(value: String) @newtype case class ItemDescription(value: String) case class Item(uuid: ItemId, name: ItemName, description: ItemDescription) }
  • 13. class ItemsCounter[F[_]: Apply]( counter: Counter[F], items: Items[F] ){ def addItem(item: Item): F[Unit] = items.add(item) *> counter.increment } class MasterMind[F[_]: Console: Monad]( itemsCounter: ItemsCounter[F], counter: Counter[F] ){ def logic(item: Item): F[Unit] = for { _ <- itemsCounter.addItem(item) c <- counter.get _ <- Console[F].println(s"Number of items: $c") } yield () } trait Counter[F[_]] { def increment: F[Unit] def get: F[Int] } trait Items[F[_]] { def getAll: F[List[Item]] def add(item: Item): F[Unit] } object TestCounter { def make[F[_]: Functor: Ref.Make]: F[Counter[F]] = Ref.of[F, Int[(0).map { ref => new Counter[F] { def increment: F[Unit] = ref.update(_ + 1) def get: F[Int] = ref.get } } object TestItems { def make[F[_]: Functor : Ref.Make]: F[Items[F]] = Ref.of[F, Map[ItemId, Item]](Map.empty).map { ref => new Items[F] { def getAll: F[List[Item]] = ref.get.map(_.values.toList) def add(item: Item): F[Unit] = ref.update(_ + (item.uuid -> item)) } } } import cats.effect.IO import cats.effect.IOApp.Simple import item.{Item, ItemDescription, ItemId, ItemName} import java.util.UUID object TestMasterMindProgram extends Simple { val item = Item( ItemId(UUID.fromString("0c69d914-6ff6-11ee-b962-0242ac120002")), ItemName("Practical FP in Scala"), ItemDescription("A great book") ) override def run: IO[Unit] = { for { counter <- TestCounter.make[IO] items <- TestItems.make[IO] itemsCounter = new ItemsCounter[IO](counter, items) masterMind = new MasterMind(itemsCounter, counter) itemsBefore <- items.getAll countBefore <- counter.get _ = assert(itemsBefore.isEmpty) _ = assert(countBefore == 0) _ <- masterMind.logic(item) itemsAfter <- items.getAll countAfter <- counter.get _ = assert(itemsAfter.sameElements(List(item))) _ = assert(countAfter == 1) } yield () } } Algebra Interpreter Program Algebra Interpreter Program Program
  • 14. Of course this was just a quick introduction to the Tagless Final technique. See the book for much more depth, and many other important aspects of using the technique. The next slide contains just a taster.
  • 15. Some might question the decision to invest in this technique for a business application, claiming it entails great complexity. This is a fair concern but let’s ask ourselves, what’s the alternative? Using IO directly in the entire application? By all means, this could work, but at what cost? At the very least, we would be giving up on parametricity† and the principle of least power. There is a huge mix of concerns. How can we possibly reason about this function? How can we even test it? We got ourselves into a very uncomfortable situation. Now let’s compare it against the abstract equivalent of it. Instead of performing side-effects, we have now typeclass constraints and capabilities. Teams making use of this technique will immediately understand that all we can do in the body of the constrained function is to compose Counter, Log, and Time actions sequentially as well as to use any property made available by the Monad constraint. It is true, however, that the Scala compiler does not enforce it so this is up to the discipline of the team. Since Scala is a hybrid language, the only thing stopping us from running wild side-effects in this function is self-discipline and peer reviews. However, good practices are required in any team for multiple purposes, so I would argue it is not necessarily a bad thing, as we can do the same thing in programs encoded directly in IO. † https://en.wikipedia.org/wiki/Parametricity
  • 16. That’s all. I hope you found it useful.