Jump to content

Draft:Cardinality (Programming Types)

From Wikipedia, the free encyclopedia

In programming languages, the term cardinality refers a property of function that indicates how many types it can return. The more types, the bigger the cardinality, being 1 the minimal if we assume that null, void and equivalents, are conceptually types.

Such property is useful when talking about how to use the function, as different returned types might require different operations.

In python, for example, two similar functions can have very different cardinalities

# Cardinality 1 -> a list of numbers
def cardinal_1(data: dic) -> list[numbers]:
    result: Optional[list[numbers]] = foo(data)
    
    return result or []
    
# Cardinality 2 -> a list of numbers or None
def cardinal_2(data: dic) -> Optional[list[numbers]]: #AKA Union[list[numbers] | None]
    result: Optional[list[numbers]] = foo(data)
    
    return result

This affects subsequent usages of the function, as each client code has to handle more than one possible type

# can handle everything as a list of numbers
def use_cardinal_1(data: dic)
    listing = cardinal_1(data)
    
    first = next(listing, None)
    
    return first
    
# each client code has to worry about the returned value
def use_cardinal_2(data: dic)
    listing = cardinal_2(data)
    
    first = next(listing, None) if listing is not None else None
    
    return first

Counting cardinalities is trickier when we consider subtypes, in this case, it might be useful to talk about ranges of cardinality, for example, supposing 4 roles that share a common parent class, we can say that the function below has 1 to 4 cardinalities, depending on its usages.

def extract_role(user: User) -> Union[Client | CS | Admin | Internal]:
    pass

References

[edit]

[1]

  1. ^ Green, Robin (Nov 5, 2010). "The cardinality of a type is the number of possible legal values that can be of that type".