quantification scalaire

Quantification in Scala

Quantification in Scala refers to the ability to express generic types that are parameterized over type constructors. It allows you to write generic code that works with different types of containers, such as lists, sets, or options.

Scala provides two types of quantification: universal quantification and existential quantification.

Universal Quantification:

Universal quantification is denoted by the forall keyword. It allows you to express that a certain property holds for all types in a given context. For example, you can define a method that works for all types that have an equals method:

def compareAll[T <: AnyRef](a: T, b: T): Boolean = a.equals(b)

In this example, T <: AnyRef is a type parameter with a type constraint that specifies that T must be a subtype of AnyRef. The forall quantifier is implied by the type constraint.

Existential Quantification:

Existential quantification is denoted by the exists keyword. It allows you to express that there exists a type that satisfies a certain property. For example, you can define a method that works with a list of elements of unknown type:

def printList(list: List[T] forSome { type T }): Unit = list.foreach(println)

In this example, List[T] forSome { type T } is an existential type that represents a list of elements of unknown type. The exists quantifier is implied by the existential type.

Higher-Kinded Types:

Scala also supports higher-kinded types, which allow you to abstract over type constructors. This enables you to write generic code that works with different types of containers. For example, you can define a generic map function that works with different types of collections:

def map[F[_], A, B](fa: F[A])(f: A => B): F[B] = fa.map(f)

In this example, F[_] is a higher-kinded type parameter that represents a type constructor. The map function can be used with different types of collections, such as lists, sets, or options.

Conclusion:

Quantification in Scala allows you to write generic code that works with different types of containers. Universal quantification is used to express properties that hold for all types in a given context, while existential quantification is used to express properties that hold for some type. Higher-kinded types enable you to abstract over type constructors and write generic code that works with different types of containers.