Plus

Plus is a concept from functional programming that extends the idea of monads and applicative functors. It adds the ability to combine two values within one context, using an operation similar to "addition". This operation is often called plus, combine, or <+>.

Main characteristics of Plus:

Examples of Plus

Plus is a powerful tool for combining values within one context. It is used in various scenarios such as merging lists, handling possible absence of values, aggregating validation or parsing results.

Formal Definition

A universally quantified semigroup.

Plus must satisfy the laws of a semigroup:

Code

trait Plus[F[_]]:
  def plus[A](fa1: F[A], fa2: => F[A]): F[A]

  def semigroup[A]: Semigroup[F[A]] = (f1: F[A], f2: F[A]) => plus(f1, f2)

Laws

The laws of Plus are analogous to the laws of a semigroup:

Example with List

given Plus[List] with
  def plus[A](fa1: List[A], fa2: => List[A]): List[A] = fa1 ++ fa2

Schema

classDiagram
    class Plus~A~{
        +plus[A](fa1: F[A], fa2: => F[A]) F[A]
    }

Library Implementations

Implementation in ScalaZ

import scalaz.*
import Scalaz.*

List(1, 2) <+> List(3, 4)                   // List(1, 2, 3, 4)

References: