Skip to content

Functional Programming Links to Sort

Functional programming links, open questions and todos from the GTD inbox notes that are not yet filed into the notes of this section. Each group says where it should end up. Fragments that have already been filed are listed at the end.

Link labels come from the URL or the original jot; the pages themselves were not checked.

Domain modeling in Haskell and Scala

These belong with Functional domain modeling once read.

Haskell:

Scala:

Sum types with sealed traits

In Scala 2 a sum type is a sealed trait with case class and case object subtypes. sealed means every subtype is declared in the same file, so the compiler knows the full list and warns when a match misses a case. The case classes are the product types. Scala 3 adds enum as shorter syntax for the same thing.

sealed trait Shape
case class Circle(r: Double) extends Shape
case class Rect(w: Double, h: Double) extends Shape

def area(s: Shape): Double = s match
  case Circle(r)  => math.Pi * r * r
  case Rect(w, h) => w * h

More in Algebraic data types; Schwarz 2020 (Library sources) works through the same encoding for DDD.

State machines

Open question: how to write a state machine functionally.

  • The states are a sum type and the events are a sum type.
  • A transition is one pure function, (State, Event) => Either[Error, State], or (State, Event) => State if every event is accepted.
  • Running the machine over a history of events is a fold: events.foldLeft(initial)(step), or a monadic fold (foldM in Cats and Haskell) for the Either version, which stops at the first rejected event. Replaying events like this is also the core of event sourcing.
  • To have the compiler reject invalid transitions instead of rejecting them at runtime, encode the state in the type (phantom types or GADTs). Signatures get more complex.

See Functional domain modeling and Folds.

Lenses and optics

A lens is a composable getter and setter for one field of an immutable structure. With nested case classes, updating person.address.street by hand needs a copy at every level; lenses for each field compose into one that does the whole update. Lenses are one kind of optic: prisms focus on one case of a sum type, traversals on many elements. The usual libraries are Monocle in Scala and lens or optics in Haskell.

No note in this section covers optics yet. If these get read, they could start one.

What “wrapper” means

Open question: the Wrapper concept and its use. The word is used in two senses.

  1. A newtype: newtype Email = Email String in Haskell, or opaque type Email = String in Scala 3. It is the same runtime value with a distinct type, so the compiler keeps the two apart. See Newtypes and simple values.
  2. Functor and monad tutorials call a context type such as Option[A] or Future[A] a wrapper: a value inside some extra structure that map and flatMap work through. The box picture breaks quickly. An IO[A], a parser or a function r -> a does not contain an A; it can produce one when run. “Context” or “computation” fits better. See Functor and map and flatMap.

Goals and languages

Idris, F*, Haskell. Three points on a scale of how much the types can say:

  • Idris has full dependent types: types can mention values, as in Vect n a, a vector of length n.
  • F* (Microsoft Research and Inria) combines dependent types with an effect system and sends proof obligations to an SMT solver. Project Everest used it, for example for the verified HACL* cryptography library.
  • Haskell has no full dependent types, but GADTs, DataKinds and type families approximate some of them.

See Refinement types and Towards dependent types.

Type safety and referential transparency as the main goals. Type safety means a well-typed program cannot hit a type error at runtime. Referential transparency means an expression can be replaced by its value without changing behaviour, which makes local reasoning, refactoring and testing straightforward (Referential transparency). Both are really means: the goal is code you can understand and change without breaking it. Formal type safety is also weaker than the everyday meaning: it rules out runtime type errors, not broken invariants. How much of the invariants to put in the types is the question of What belongs in the type system.

Metaprogramming. Code that generates or inspects code at compile time. Scala 3 has inline, quoted macros and type class derivation with derives; Scala 2 macros cannot be used from Scala 3. Haskell has Template Haskell and GHC.Generics. In FP the most common use is deriving type class instances (JSON codecs, Show, Eq) instead of writing them by hand.

Scala and FP articles

These were collected together in the inbox. Pages whose topic is given were not opened; the topic comes from the URL or the original jot.

Study plan and todos

  • Read two or three Haskell books. Candidates already in the library: Allen and Moronuki 2016 as the main course, Serrano Mena 2021 for monads, transformers and effects, and Bird and Gibbons 2020 for algorithms with equational reasoning.
  • Add Haskell to the resume. One finished, published Haskell project is stronger evidence than books; Project ideas has ideas of that size.
  • Investigate leetcode_tracker with ChatGPT.
  • Do the task from this video: https://www.youtube.com/watch?v=Ae2HR-qD1UE&t=1371s
  • List the Scala and FP features to use in projects.

Kept as motivation:

Over time you’ll come to understand the Scala/FP thought process; you’ll discover that one concept logically leads to another.

Already filed

These inbox fragments now live in other notes:

Library sources

  • Schwarz 2020, Scala 3 by Example: ADTs for DDD, Part 1: sealed traits and enums as sum types.
  • Volpe 2021, Practical FP in Scala (2nd edition): tagless final, newtypes and refinement types in a full application.
  • Welsh and Gurnell 2020, Scala with Cats: type classes and implicit scope, functors and monads in Scala.
  • Odersky et al. 2021, Programming in Scala (5th edition): givens and using clauses. Its section 9.1, the file matcher, is discussed in Custom control structures.
  • Rosien 2021, Essential Effects: Cats Effect IO, programs as values, parallelism and resources.
  • Vargas 2023, Why on earth a ZIO IO monad for Scala?: a saved Medium article, now used in Effect systems.
  • Serrano Mena 2021, Book of Monads (2nd edition): final, initial and free-monad styles side by side.
  • Milewski 2019, Category Theory for Programmers (Scala edition): functors and natural transformations.
  • Serrano Mena 2022, Haskell: Almost Standard Libraries: chapter 10, Optics. Section 10.1, “Lenses, prisms, (affine) traversals, folds”, builds lenses with makeLenses and uses view, set and over (% in optics, . in lens and microlens). It covers affine traversals for fields only some constructors have (preview), prisms for constructors (review), traversals with each, and folds, and explains why a lens composed with a prism is only an affine traversal. Section 10.2, “Focusing on JSON documents”, covers aeson-optics on untyped JSON; on Lenses and optics.

Further reading:

  • Allen and Moronuki 2016, Haskell Programming from First Principles
  • Bird and Gibbons 2020, Algorithm Design with Haskell
  • Nielson and Nielson 1999, Type and Effect Systems
  • Bragilevsky 2021, Haskell in Depth: section 13.2.3, “Dependent types and substituting them with singletons”, encodes door states in types with singletons, so that closing a closed door doesn’t compile, on State machines; section 14.2.3, “Accessing data with lenses”, introduces lens, Lens for products and Prism for sums, on Lenses and optics; sections 12.2, “Data-type-generic programming”, and 12.3, “Template Haskell and quasiquotes” (GHC.Generics, Template Haskell), and the opening of 13.2 (Haskell’s types approximate dependent types; progress and preservation in 13.2.1), on Goals and languages.