User:Ashalkhakov/Functional Programming/Types

Types
Not all expressions formed using the syntactical rules of ATS are "good". Some expressions, such as  are considered as nonsensical as its not clear what they should evaluate to. What does it mean to add an integer to a boolean? You can define some way to "add" booleans and integers, but that operation would be inherently different from the operations of adding integers to integers and adding booleans to booleans (that is, computing their logical "or"), and we assume that you find that maintaining such distinctions is valuable. As another example, evaluating  (as defined in the previous subsections) will never give us any result (as the function, given a negative integer on input, will never reach the base case). There are many other examples of program behavior that we'd better avoid, as we certainly don't want our programs, when executed, to produce unwanted results (such as corrupting memory, going into an infinite loop, not freeing the allocated memory, or producing values that we deem incorrect -- bear in mind this list is in-exhaustive).

There is clearly a need to know precisely which expressions make sense and which don't, and this is what the type system is used for. Basically, it is a set of formal rules for determining if a given expression, when executed, will not bring some unwanted behavior. Expressions are assigned types, which are used to group data of the same kind (in other words, data are classified by types). We have seen that integers such as,   and   are assigned type   (the justification is that these constants share one thing: they all denote integers). Another kind of values are the booleans  and. We say that an expression is "good" if it can be assigned a type according to the typing rules and the process of checking whether an expression really has the type assigned to it by the programmer is called type checking. The notion of a "good" expression, for now, is left at the intuitive level and we will refine it later.

The question whether a program satisfies the typing rules can be enforced by the compiler without programmer intervention. In ATS, type-checking is performed early (as it is said, statically), that is, before the program is run.

We have seen some basic types ( and  ) that are assigned to primitive constants. Types for functions are specified by ascribing type to each argument as well as the result using the  syntax, where   (for   between   and  ) and   stand for some other types. The types given to the formal arguments of a function specify the domain the function is defined on, whereas the type given to the function result specifies the range (codomain) of the function.