Sample programming book booklet pamphlet, Cheat Sheet of Biology

Sample programming book booklet pamphlet

Typology: Cheat Sheet

2020/2021

Uploaded on 11/14/2021

strengthftw
strengthftw 🇺🇸

2 documents

1 / 30

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e

Partial preview of the text

Download Sample programming book booklet pamphlet and more Cheat Sheet Biology in PDF only on Docsity!

Practical FP in Scala

A hands-on approach

Gabriel Volpe

August 1, 2021

Second Edition

  • Preface
  • Acknowledgments
    • People
    • Software
    • Fonts
  • Dependency versions
  • Prerequisites
  • How to read this book
    • Conventions used in this book
  • Chapter 1: Best practices
    • Strongly-typed functions
      • Value classes
      • Newtypes
      • Refinement types
      • Runtime validation
    • Encapsulating state
      • In-memory counter
    • Sequential vs concurrent state
      • State Monad
      • Atomic Ref
    • Shared state
      • Regions of sharing
      • Leaky state
    • Anti-patterns
      • Seq: a base trait for sequences
      • About monad transformers
      • Boolean blindness
    • Error handling
      • MonadError & ApplicativeError
      • Either Monad
      • Classy prisms
    • Summary
  • Chapter 2: Tagless final encoding Contents
    • Algebras
      • Naming conventions
    • Interpreters
      • Building interpreters
    • Programs
    • Implicit vs explicit parameters
      • Achieving modularity
      • Implicit convenience
      • Capability traits
    • Why Tagless Final?
      • Parametricity
      • Comparison
    • Summary
  • Chapter 3: Shopping Cart project
    • Business requirements
      • Third-party payments API
      • Identifying the domain
      • Identifying HTTP endpoints
    • Technical stack
      • A note on Cats Effect
    • Summary
  • Chapter 4: Business logic
    • Identifying algebras
    • Data access and storage
      • Health check
    • Defining programs
      • Checkout
      • Retrying effects
    • Architecture
    • Summary
  • Chapter 5: HTTP layer
    • A server is a function
    • HTTP Routes #1
    • Authentication
      • JWT Auth
    • HTTP Routes #2
    • Composition of routes
    • Middlewares
      • Compositionality
    • HTTP server
    • Entity codecs Contents
    • HTTP client
      • Payment client
      • Creating a client
    • Summary
  • Chapter 6: Typeclass derivation
    • Standard derivations
    • JSON codecs
      • Map codecs
    • Orphan instances
    • Identifiers
      • GenUUID & IsUUID
      • Custom derivation
    • Validation
    • Http4s derivations
    • Higher-kinded derivations
    • Summary
  • Chapter 7: Persistent layer
    • Skunk & Doobie
      • Session Pool
      • Connection check
      • Queries
      • Commands
      • Interpreters
      • Streaming & Pagination
    • Redis for Cats
      • Connection
      • Interpreters
    • Health check
    • Blocking operations
    • Transactions
      • Compositionality
    • Summary
  • Chapter 8: Testing
    • Functional test framework
    • Generators
      • About forall
      • Application data
    • Business logic
      • Happy path
      • Expectations
      • Empty cart Contents
      • Unreachable payment client
      • Recovering payment client
      • Failing orders
      • Failing cart deletion
    • HTTP
      • Routes
      • Clients
    • Law testing
    • Integration tests
      • Shared resources
      • Postgres
      • Redis
    • Summary
  • Chapter 9: Assembly
    • Logging
    • Tracing
      • Ecosystem
    • Configuration
    • Modules
    • Resources
    • Main
    • Summary
  • Chapter 10: Ship it!
    • Docker image
      • Optimizing image
      • Run it locally
    • Continuous Integration
      • Dependencies
      • CI build
      • Nix Shell
      • Furthermore
    • Summary
  • Bonus Chapter
    • MTL (Monad Transformers Library)
      • Managing state
      • Accessing context
    • Optics
      • Lenses
      • Prisms
  • Aspect Oriented Programming Contents
    • Tofu’s Mid
  • Concurrency
    • Producer-Consumer
    • Effectful streams
    • Interruption
    • Multiple subscriptions
    • (Un)Cancelable regions
    • Resource safety
    • Finite State Machine
  • Summary

Preface

Scala is a hybrid language that mixes both the Object-Oriented Programming (OOP) and Functional Programming (FP) paradigms. This allows you to get up-and-running pretty quickly without knowing the language in detail. Over time, as you learn more, you are hopefully going to appreciate what makes Scala great: its functional building blocks.

Pattern matching, folds, recursion, higher-order functions, etc. If you decide to continue down this road, you will discover the functional subset of the community and its great ecosystem of libraries.

Sooner rather than later, you will come across the Cats^1 library and its remarkable documentation. You might even start using it in your projects! Once you get familiar with the power of typeclasses such as Functor, Monad, and Traverse, I am sure you will love it.

As you evolve into a functional programmer, you will learn about functional effects and referential transparency. You might as well start using the popular IO Monad present in Cats Effect^2 and other similar libraries.

One day you will need to process a lot of data that doesn’t fit into memory; a suitable solution to this engineering problem is streaming. While searching for a valuable can- didate, you might stumble upon a purely functional streaming library: Fs2^3. You will quickly learn that it is also a magnificent library for control flow.

A requirement to build a RESTful API^4 will more likely come down your way early on in your career. Http4s^5 leverages the power of Cats Effect and Fs2 so you can focus on shipping features while remaining on functional land.

You might decide to adopt a message broker as a communication protocol between microservices and to distribute data. You name it: Kafka, Pulsar, RabbitMQ, to mention a few. Each of these wonderful technologies has a library that can fulfill every client’s needs.

(^1) https://typelevel.org/cats (^2) https://typelevel.org/cats-effect (^3) https://fs2.io (^4) https://restfulapi.net/ (^5) https://http4s.org/

Acknowledgments

One can only dream of starting writing a book and making it over the finish line. Yet, I managed to do this twice! Though, this would have been an impossible task without the help of many people that had supported me over time, as well as many open-source and free software I consider indispensable.

I am beyond excited and can only be thankful to all of you.

Acknowledgments

People

I consider myself incredibly lucky to have had all these great human beings influencing the content of this book one way or another. This humble piece of work is dedicated:

  • To my beloved partner Alicja for her endless support in life.
  • To my friend John Regan for his invaluable feedback, which has raised the bar on my writing skills to the next level.
  • To the talented @impurepics^1 , author of the book’s cover.
  • To Jakub Kozłowski for reviewing almost every pull request of the book and the Shopping Cart application.
  • To my OSS friends, Fabio Labella, Frank Thomas, Luka Jacobowitz, Michael Pilquist, Oleg Nizhnik, Olivier Mélois, Piotr Gawryś, Rob Norris, and Ross A. Baker, both for their priceless advice and for proofreading some of the drafts.
  • To the +1500 early readers who supported my work for the extra motivation and the early feedback.
  • To all the amazing volunteers that have provided incredible reviews in this second edition: Adianto Wibisono, Barış Yüksel, Bartłomiej Szwej, Bjørn Madsen, Mark Mynsted, Pavels Sisojevs, and Sinan Pehlivanoglu.

Last but not least, this edition is dedicated to all the people that make the Typelevel ecosystem as great as it is nowadays, especially to the maintainers and contributors of my two favorite Scala libraries: Cats Effect and Fs2. This book wouldn’t exist without all of your work! #ScalaThankYou

Although the book was thoroughly reviewed, I am the sole responsible for all of the opinionated sentences, and any remaining mistakes are only mine.

(^1) https://twitter.com/impurepics

Acknowledgments

Fonts

This book’s main font is Latin Modern Roman^5 , distributed under The GUST Font License (GFL)^6. Other fonts in use are listed below.

  • JetBrainsMono^7 for code snippets, available under the SIL Open Font License 1.1^8
  • Linux Libertine^9 for some Unicode characters, licensed under the GNU General Public License version 2.0 (GPLv2)^10 and the SIL Open Font License^11.

(^5) https://tug.org/FontCatalogue/latinmodernroman/ (^6) https://www.ctan.org/license/gfl (^7) https://www.jetbrains.com/lp/mono/ (^8) https://github.com/JetBrains/JetBrainsMono/blob/master/OFL.txt (^9) https://sourceforge.net/projects/linuxlibertine/ (^10) https://opensource.org/licenses/gpl-2.0.php (^11) https://scripts.sil.org/cms/scripts/page.php?item_id=OFL

Dependency versions

At the moment of writing, all the standalone examples use Scala 2.13.5 and sbt 1.5.3, as well as the following dependencies defined in this minimal build.sbt^1 file.

ThisBuild / scalaVersionႍ := "2.13.5"

lazy val root = (project in file(".")) .settings( nameႍ := "minimal", libraryDependenciesႍ ++= Seq( compilerPlugin( "org.typelevel" %% "kind-projector" % "0.12.0" cross CrossVersion.full ), "org.typelevel" %% "cats-core" % "2.6.1", "org.typelevel" %% "cats-effect" % "3.1.1", "org.typelevel" %% "cats-mtl" % "1.2.1", "co.fs2" %% "fs2-core" % "3.0.3", "dev.optics" %% "monocle-core" % "3.0.0", "dev.optics" %% "monocle-macro" % "3.0.0", "io.estatico" %% "newtype" % "0.4.4", "eu.timepit" %% "refined" % "0.9.25", "eu.timepit" %% "refined-cats" % "0.9.25", "tf.tofu" %% "derevo-cats" % "0.12.5", "tf.tofu" %% "derevo-cats-tagless" % "0.12.5", "tf.tofu" %% "derevo-circe-magnolia" % "0.12.5", "tf.tofu" %% "tofu-core-higher-kind" % "0.10.2" ), scalacOptionsႍ ++= Seq( "-Ymacro-annotations", "-Wconf:cat=unused:info" )

The sbt-tpolecat plugin is also necessary. Here is a minimal plugins.sbt file.

addSbtPlugin("io.github.davidgregory084" % "sbt-tpolecat" % "0.1.17")

(^1) https://gist.github.com/gvolpe/04b31a5caa875f8f16bcd1d12b72face

Prerequisites

This book is considered intermediate to advanced. Familiarity with functional program- ming concepts and basic FP libraries such as Cats and Cats Effect will be of tremendous help even though I will do my best to be as clear and concise as I can.

Both Scala with Cats^1 and Essential Effects^2 , in that order, are excellent books to learn these concepts. The official documentation of Cats Effect^3 is also a great resource.

The following list details the topics required to understand this book.

  • Higher-Kinded Types (HKTs)^4.
  • Typeclasses^5.
  • IO Monad^6.
  • Referential Transparency^7.

Unfortunately, these topics are quite lengthy to be explained in this book, so readers are expected to be acquainted with them. However, some examples will be included, and this might be all you need.

If the requirements feel overwhelming, it is not because the entire book is difficult, but rather because some specific parts might be. You can try to read it, and if at some point you get stuck, you can skip that section. You could also make a pause, go to read about these resources, and then continue where you left off.

Remember that we are going to develop an application together, which will help you learn a lot, even if you haven’t employed these techniques and libraries before.

(^1) https://underscore.io/books/scala-with-cats/ (^2) https://essentialeffects.dev/ (^3) https://typelevel.org/cats-effect/ (^4) https://typelevel.org/blog/2016/08/21/hkts-moving-forward.html (^5) https://typelevel.org/cats/typeclasses.html (^6) https://typelevel.org/blog/2017/05/02/io-monad-for-cats.html (^7) https://en.wikipedia.org/wiki/Referential_transparency

How to read this book

For conciseness, most of the imports and some datatype definitions are elided from the book, so it is recommended to read it by following along the two Scala projects that supplement it.

  • pfps-examples^1 : Standalone examples.
  • pfps-shopping-cart^2 : Shopping cart application.

The first project includes self-contained examples that demonstrate some features or techniques explained independently.

The latter contains the source code of the full-fledged application that we will develop in the next ten chapters, including a test suite and deployment instructions.

Bear in mind that the presented Shopping Cart application only acts as a guideline. To get a better learning experience, readers are encouraged to write their own application from scratch; getting your hands dirty is the best way to learn.

There is also a Gitter channel^3 where you are welcome to ask any kind of questions related to the book or functional programming in general.

(^1) https://github.com/gvolpe/pfps-examples (^2) https://github.com/gvolpe/pfps-shopping-cart (^3) https://gitter.im/pfp-scala/community

Chapter 1: Best practices

Before we get to analyzing the business requirements and writing the application, we are going to explore some design patterns and best practices. A few well-known; others not so standard and biased towards my preferences.

These will more likely appear at least once in the application we will develop, so you can think of this chapter as a preparation for what’s to come.

Chapter 1: Best practices

Strongly-typed functions

One of the most significant benefits of functional programming is that it lets us rea- son about functions by looking at their type signature. Yet, the truth is that these are commonly created by us, imperfect humans, who often end up with weakly-typed functions.

For instance, let’s look at the following function.

def lookup(username: String, email: String): F[Option[User]]

Do you see any problems with it? Let’s see how we can use it.

$ lookup("[email protected]", "aeinstein") $ lookup("aeinstein", "123") $ lookup("", "")

See the issue? It is not only easy to confuse the order of the parameters but it is also straightforward to feed our function with invalid data! So what can we do about it? We could make this better by introducing value classes.

Value classes

In vanilla Scala, we can wrap a single field and extend the AnyVal abstract class to avoid some runtime costs. Here is how we can define value classes for username and email.

case class Username(val value: String) extends AnyVal case class Email(val value: String) extends AnyVal

Now we can re-define our function using these types.

def lookup(username: Username, email: Email): F[Option[User]]

Notice that we can no longer confuse the order of the parameters.

$ lookup(Username("aeinstein"), Email("[email protected]"))

Or can we?

$ lookup(Username("[email protected]"), Email("aeinstein")) $ lookup(Username("aeinstein"), Email("123")) $ lookup(Username(""), Email(""))

Fine, we are doing this on purpose. However, in a statically-typed language, we would expect the compiler to help prevent this but it cannot due to lack of information. A way to communicate our intentions to the compiler is to make the case class constructors private only expose smart constructors.