IsEmpty
IsEmpty is a concept from functional programming that extends PlusEmpty,
adding an emptiness-checking operation.
It allows determining whether a value within a certain context is "empty"
(e.g., absence of a value, an empty list, a failed computation, etc.).
Main characteristics of IsEmpty:
- Checking for "empty":
The
isEmptyoperation returnstrueif a value is "empty" andfalseotherwise. - Relationship to the "empty" value:
An "empty" value (
empty[A]) must always be recognized by theisEmptyoperation as "empty". - Relationship to the combining operation:
The result of combining two values via
plus(or<+>) is "empty" only if both original values were "empty".
Examples of IsEmpty
- Lists (
List). Imagine you have a list of numbers. TheisEmptyoperation allows checking whether the list is empty. For example, for the list[1, 2, 3]the result isfalse, and for an empty list[]it istrue. - Parsers.
Imagine you have a parser that parses input data. The
isEmptyoperation allows checking whether the parser returned an error (which can be considered an "empty" result). - Validators.
Imagine you have a validator that checks data correctness.
The
isEmptyoperation allows checking whether the validator returned an error (which can be considered an "empty" result).
Formal Definition
IsEmpty is a type class that allows checking whether a type with an empty representation is truly empty.
Extends PlusEmpty.
The laws of isEmpty (besides the parent laws) describe how the emptiness-checking operation should behave:
- An "empty" value must always be recognized as "empty":
isEmpty(empty[A]) = true. In other words, if you check whether the valueempty[A]is "empty", the result should betrue. - The result of combining two values is "empty" only when both values are "empty":
isEmpty(fa1) && isEmpty(fa2) == isEmpty(plus(fa1, fa2)).isEmptyover a composition of two functors istrueif and only ifisEmptyof each functor istrue: In other words, if you combine two values usingplus, the result will be "empty" only when both values were "empty".
Code
trait IsEmpty[F[_]] extends PlusEmpty[F]:
def isEmpty[A](fa: F[A]): Boolean
Laws
- An "empty" value must always be recognized as "empty":
isEmpty(empty[A]) = true. - The result of combining two values is "empty" only when both values are "empty":
isEmpty(fa1) && isEmpty(fa2) == isEmpty(plus(fa1, fa2)).
Example with List
given IsEmpty[List] with
override def isEmpty[A](fa: List[A]): Boolean = fa.isEmpty
override def plus[A](fa1: List[A], fa2: => List[A]): List[A] = fa1 ++ fa2
override def empty[A]: List[A] = List.empty[A]
Schema
classDiagram
class Plus~A~{
+plus[A](fa1: F[A], fa2: => F[A]) F[A]
}
class PlusEmpty~A~{
+empty[A]: F[A]
}
Plus <|-- PlusEmpty
class IsEmpty~A~{
+isEmpty[A](fa: F[A]) Boolean
}
PlusEmpty <|-- IsEmpty
Library Implementations
Implementation in ScalaZ
import scalaz.*
import Scalaz.*
// ... All parent operations
summon[IsEmpty[List]].isEmpty(List.empty[Int]) // true
References: