Covariance and contravariance (computer science): Difference between revisions

Content deleted Content added
m upd link
m OCaml does not permit types to be capitalized.
Line 91:
 
== Function types ==
Languages with [[first-class function]]s have [[function type]]s like "a function expecting a Cat and returning an Animal" (written {{OCaml|Catcat -> Animalanimal}} in [[OCaml]] syntax or {{C sharp|Func<Cat,Animal>}} in [[C Sharp (programming language)|C#]] syntax).
 
Those languages also need to specify when one function type is a subtype of another&mdash;that is, when it is safe to use a function of one type in a context that expects a function of a different type.
It is safe to substitute a function ''f'' for a function ''g'' if ''f'' accepts a more general type of argument and returns a more specific type than ''g''. For example, functions of type {{OCaml|Animalanimal -> Catcat}}, {{OCaml|Catcat -> Catcat}}, and {{OCaml|Animalanimal -> Animalanimal}} can be used wherever a {{OCaml|Catcat -> Animalanimal}} was expected. (One can compare this to the [[robustness principle]] of communication: "be liberal in what you accept and conservative in what you produce.") The general rule is:
 
:<math>(P_1 \rightarrow R_1) \leq (P_2 \rightarrow R_2)</math> if <math>P_1 \geq P_2</math> and <math>R_1 \leq R_2</math>.