Bifunctor Group

Introduction

In functional programming, type classes play a key role in providing abstractions for working with various data types. One such type class is Bifunctor, which generalizes the ability to apply functions to two types contained within a single context. In Scala, as in other functional languages, Bifunctor provides a powerful tool for working with types that have two parameters, such as Either, Tuple2, or user-defined bifunctors.

The Bifunctor type class allows applying functions to each of the two types while preserving the container structure. This is especially useful when it is necessary to transform both types independently of each other without destroying the overall data structure. In this section we will consider how Bifunctor is defined and used, as well as study examples of its application for various data types.

Usage

Bifunctors find application in various areas of functional programming, especially where work with types having two parameters is required. They provide a convenient way to transform both types while preserving the container structure. Here are several examples where bifunctors can be useful:

Diagram

classDiagram
        Bifunctor <|-- Bitraverse
        Bifoldable <|-- Bitraverse
        class Bifunctor~F[_, _]~{
            +bimap[A, B, C, D](fab: F[A, B])(f: A => C, g: B => D) F[C, D]
            +leftMap[A, B, C](fab: F[A, B])(f: A => C) F[C, B]
            +rightMap[A, B, D](fab: F[A, B])(g: B => D) F[A, D] 
        }
        class Bifoldable~F[_, _]~{
            +bifoldMap[M](fa: F[A, B])(f: A => M)(g: B => M)(using ma: Monoid[M]) M
            +bifoldRight[C](fa: F[A, B])(z: => C)(f: (A, C) => C)(g: (B, C) => C) C
            +bifoldLeft[C](fa: F[A, B])(z: C)(f: (C, A) => C)(g: (C, B) => C) C
        }
        class Bitraverse~F[_, _]~{
            +bitraverse[G[_]: Applicative, C, D](fab: F[A, B])(f: A => G[C], g: B => G[D]) G[F[C, D]]
            +bisequence[G[_]: Applicative, A, B](fab: F[A, B])(x: F[G[A], G[B]]) G[F[A, B]]
        }

References: