Cats Documentation

repository·main·Indexed 26 days ago

https://github.com/typelevel/cats

A fundamental library for functional programming in Scala providing essential abstractions like type classes and functional patterns. It includes core modules such as cats-core, cats-kernel, and cats-laws, as well as specialized tools like IorT for error accumulation, Eval for controlled laziness, and the algebra package for representing mathematical structures. Compatible with JVM, Scala.js, and Scala Native.

Tokens
56.9K
Snippets
162
Records
287
Agent score
89%

What's inside Cats

  1. Overview of Cats

    main
    Cats is a library providing core functional programming abstractions for the Scala programming language. It is designed to be binary compatible, modular, approachable, and efficient, serving as a foundation for a broader ecosystem of pure, typeful functional programming libraries in Scala.
  2. Understand Type Classes and Ad-hoc Polymorphism

    main
    Type classes enable ad-hoc polymorphism (overloading) in functional programming. Unlike object-oriented subtyping, type classes allow you to define behavior for a type without modifying the type itself. This is achieved by separating the data (the type) from the behavior (the type class instance).
  3. Use the Reducible type class

    main

    The Reducible type class extends Foldable to provide reduction methods that do not require an initial value (unlike fold). This makes it ideal for abstracting over non-empty collections like NonEmptyList or NonEmptyVector.

    Key characteristics:

    • Unlike Foldable which requires a Monoid (for fold), Reducible only requires a Semigroup (for reduce).
    • It provides guarantees that operations won't throw exceptions on empty collections when used with non-empty types.
    • It includes eager reduction (reduceLeft) and lazy reduction (reduceRight) using Eval.
    import cats._
    import cats.data._
    import cats.syntax.all._
    
    // Example usage with NonEmptyList
    Reducible[NonEmptyList].reduce(NonEmptyList.of("a", "b", "c"))
  4. Understand the Validated data type

    main

    The Validated[+E, +A] data type is used for error accumulation. It is similar to Either, but unlike Either (which is a Monad and follows a fail-fast approach), Validated is an Applicative Functor. This allows it to collect multiple errors instead of stopping at the first one encountered.

    It has two projections:

    • Valid[+A](a: A): Represents a successful computation.
    • Invalid[+E](e: E): Represents a failed computation containing error(s).

    Note: Because it is not a Monad, you cannot use for-comprehensions (which rely on flatMap) to compose Validated instances. Instead, you must use Applicative syntax like .mapN.

    sealed abstract class Validated[+E, +A] extends Product with Serializable
    
    final case class Valid[+A](a: A) extends Validated[Nothing, A]
    final case class Invalid[+E](e: E) extends Validated[E, Nothing]
  5. Understand the Foldable type class

    main

    The Foldable[F] type class is implemented for data structures that can be folded into a summary value. It is primarily built upon two core methods:

    • foldLeft(fa, b)(f): Performs an eager, left-associative fold over fa.
    • foldRight(fa, b)(f): Performs a lazy, right-associative fold over fa.

    For a collection like List(1, 2, 3) with a starting value 0 and addition +:

    • foldLeft executes as ((0 + 1) + 2) + 3.
    • foldRight executes as 0 + (1 + (2 + 3)).

    If you are defining a new data structure, providing implementations for foldLeft and foldRight allows you to automatically gain access to a wide range of other Foldable operations.

  6. Understand NonEmptyList

    main

    A NonEmptyList[A] is a specialized data type that guarantees at least one element exists by construction. This makes it a safer alternative to List[A] for operations that are undefined for empty collections (like head).

    Key benefits:

    • Totality: Operations like head and tail are always well-defined because an empty NonEmptyList cannot be created.
    • Error Reporting: It is ideal for use with Validated or Ior to ensure that an Invalid state always contains at least one error.
    • Domain Logic: It allows you to move validation to the boundaries of your program, enabling functions to accept NonEmptyList instead of List and Option, thus avoiding unnecessary null/empty checks in your core logic.
  7. Understand and use the Ior data type

    main

    The Ior[A, B] data type represents an inclusive-or relationship. Unlike Either, which is exclusive (either A or B), an Ior can contain an A, a B, or both an A and a B.

    Ior is right-biased, meaning map and flatMap operate on the right side (B). When using Monad or Applicative instances, Ior accumulates values on the left side (requiring a Semigroup for A), similar to how Validated works. This allows you to accumulate non-fatal warnings on the left while continuing with the computation on the right.

    import cats.data._
    
    val right = Ior.right[String, Int](3)
    val left = Ior.left[String, Int]("Error")
    val both = Ior.both("Warning", 3)
  8. Understand Kleisli as a Monad Transformer

    main
    In Cats, Kleisli[F, A, B] can be viewed as a monad transformer for functions. It represents a function of type A => F[B]. This allows you to compose the monadic properties of F[_] with the function's input/output, enabling you to work with nested contexts or effects (like Option, Either, or List) within a function's execution flow.
  9. Explore the Typelevel Ecosystem libraries

    main

    The Typelevel ecosystem includes a variety of specialized Scala libraries for functional programming. Key libraries include:

    • sttp: A Scala HTTP client.
    • sup: Composable, purely functional healthchecks.
    • tsec: Typesafe, functional, general purpose cryptography and security.
    • vault: Type-safe, persistent storage for values of arbitrary types.
    • upperbound: A purely functional, interval-based rate limiter with backpressure support.
    • streamz: Conversion between Akka Streams and Fs2 Streams/Pipes/Sinks, and support for Apache Camel endpoints.
    • synchronized: Synchronous resource access.
    • system-effect: Console and Environment Simple Tools.
    • testcontainers-specs2: Test Containers support for Specs2.
    • unique: Unique functional values for Scala.
    • vinyldns: DNS governance system using Fs2 for throttling updates.
    • whale-tail: Docker Daemon Integration.
  10. Use the Writer datatype for logging computations

    main

    The Writer[L, A] datatype represents a computation that produces a tuple containing a value of type A (the output) and a value of type L (the logging side). When composing operations like flatMap, the logs are automatically combined using an implicit Semigroup[L].

    To access the contents of a Writer, use the .run method.

    import cats.data.Writer
    import cats.instances._
    
    val mapExample = Writer("map Example", 1).map(_ + 1)
    
    mapExample.run
  11. Understand the `Const` data type

    main

    The Const[A, B] data type is a container that stores a value of type A but carries a phantom type parameter B. The type parameter B is not used in the data structure itself, but it allows you to carry type information through functional transformations. It behaves similarly to the const function, which returns the first argument and ignores the second.

    case class Const[A, B](getConst: A)
  12. Explore the Typelevel Ecosystem libraries

    main

    The Typelevel ecosystem consists of various purely functional libraries designed to work together. This segment of the ecosystem includes tools for parsing, concurrency, JSON manipulation, and more:

    • Mules: In-memory caching.
    • agitation: Cooperative Cancelation for Cats Effect.
    • ancient-concurrent: Cats Effect concurrency for cats-effect 0.10.
    • atto: Friendly text parsers.
    • bank: Concurrent Vault Management.
    • canoe: Purely functional library for building Telegram chatbots.
    • Cats Effect: High-performance, asynchronous, composable framework for building real-world applications in a purely functional style.
    • cats-effect-testing: Experimental integration between Cats Effect and testing frameworks.
    • cats-effect-time: Java Time for Cats Effect.
    • cats-parse: A parsing library for the Cats ecosystem.
    • cats-retry: Composable retry logic for Cats and Cats Effect.
    • cats-scalacheck: Cats typeclass instances for ScalaCheck.
    • cats-stm: Software Transactional Memory for Cats Effect.
    • cats-time: Cats typeclass instances for java.time.
    • chromaprint: Scala implementation of Chromaprint/AcoustID audio fingerprinting, built with Fs2 streams and Cats Effect.
    • circe-fs2: Streaming JSON manipulation with Circe.
    • Circe: Pure functional JSON library.
    • circuit: Functional Circuit Breaker implementation.