TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

What are covariance and contravariance?

235 pointsby beyangalmost 8 years ago

17 comments

rntzalmost 8 years ago
Covariance and contravariance are just monotonicity and anti-monotonicity, applied to types ordered by subtyping.<p>That is: if we have a function <i>on types</i>, say, the function `f` defined by:<p><pre><code> f(x) = Int -&gt; x </code></pre> Then we say `f` is covariant because it is monotone: it preserves the subtype ordering on its argument. That is:<p><pre><code> if x &lt;: y, then f(x) &lt;: f(y) </code></pre> Similarly, if we consider `f` defined by:<p><pre><code> f(x) = x -&gt; Int </code></pre> then this `f` is contravariant because it is anti-monotone: it reverses the subtype ordering on its argument. That is:<p><pre><code> if x &lt;: y, then f(y) &lt;: f(x) </code></pre> People tend to find covariance more intuitive than contravariance; unless the issue is pointed out, they tend to assume everything is covariant. They see a type, say:<p><pre><code> dog -&gt; dog </code></pre> and they assume &quot;oh, every dog is an animal, so I can put &#x27;animal&#x27; in place of &#x27;dog&#x27; and it&#x27;ll be more general (i.e. a supertype)&quot;. This is false, as the article points out.
评论 #14838618 未加载
评论 #14836778 未加载
评论 #14837316 未加载
评论 #14835737 未加载
评论 #14837567 未加载
joshlemeralmost 8 years ago
Also see this handy infographic <a href="https:&#x2F;&#x2F;i.stack.imgur.com&#x2F;W879X.png" rel="nofollow">https:&#x2F;&#x2F;i.stack.imgur.com&#x2F;W879X.png</a>
评论 #14835283 未加载
tunesmithalmost 8 years ago
One of the ways I like to look at it is that I&#x27;m a foreman and one of my construction workers can&#x27;t show up, and I need a substitute, I don&#x27;t want someone that is even less useful than my worker. A really good substitute is someone that can do everything that my original worker could do, and maybe then some even if I don&#x27;t take advantage of it. Meanwhile, I don&#x27;t want his results to be <i>worse</i> than my original worker&#x27;s, but I sure don&#x27;t mind if it&#x27;s better.<p>In other words, if my original worker only knows how to turn a Dog into a Dog, and that was good enough, the most useful substitute is someone who can take any Animal and turn it into any special kind of dog.<p>Or maybe I care about 2x4&#x27;s, and my normal guy only knows how to turn Cherry into 2x4&#x27;s and isn&#x27;t trained on anything else, even though that suited my needs. The best sub is someone who can take lots of kinds of wood and turn it into different kinds of posts and planks; I&#x27;m just only taking advantage of his 2x4 skills.<p>Unfortunately a lot of programmers design subclasses by saying &quot;hey look, I&#x27;m good at starting with a schnauzer&quot; or &quot;hey look, I&#x27;m good at starting with <i>Brazilian</i> cherry&quot;. These guys aren&#x27;t helpful when they show up in your parameter list.
评论 #14838760 未加载
quantdevalmost 8 years ago
This was very interesting.<p>As a mathematician with no comp-sci type knowledge, my only understanding of inheritance is the &quot;is a&quot; rule. Using this, I realized that a subtype of the set of functions from Dog to Dog must be a set of functions such that each function could be treated as a function from Dog to Dog under an appropriate restriction. This would be the only way for such a set to satisfy what felt like the &quot;is a&quot; inheritance rule.<p>In other words, a set of functions from A to B where Dog is contained in A and B is contained in Dog would be a subtype of the set of functions from Dog to Dog. So Animals -&gt; Greyhound works.
评论 #14835520 未加载
nooberminalmost 8 years ago
So I used to think covariance and contravariance were related to covectors and vectors from physics, but in fact, our terminology is in fact confusing the concept (almost &quot;opposite&quot; actually) that is now accepted in math. (See comment on wiki[0]).<p>There we physicists go, confusing things again.<p>[0] <a href="https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;Functor#Covariance_and_contravariance" rel="nofollow">https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;Functor#Covariance_and_contrav...</a>
评论 #14836510 未加载
评论 #14835012 未加载
ducttapecrownalmost 8 years ago
Why are covariance and contravariance important, and how do their type theory definitions differ from mathematical or statistical definitions of covariance and contravariance?<p>Is it just a distinction of which direction the type hierarchy flows, and the consequences that must have with regard to functions in order for logical consistency to be maintained?
评论 #14835884 未加载
评论 #14835350 未加载
the_mitsuhikoalmost 8 years ago
Microsoft probably has the most logical docs on that: <a href="https:&#x2F;&#x2F;docs.microsoft.com&#x2F;en-us&#x2F;dotnet&#x2F;csharp&#x2F;programming-guide&#x2F;concepts&#x2F;covariance-contravariance&#x2F;" rel="nofollow">https:&#x2F;&#x2F;docs.microsoft.com&#x2F;en-us&#x2F;dotnet&#x2F;csharp&#x2F;programming-g...</a>
pathikritalmost 8 years ago
My quick and dirty tl;dr: <a href="https:&#x2F;&#x2F;gist.github.com&#x2F;pathikrit&#x2F;a7845f72645159646fdb632bc334771a" rel="nofollow">https:&#x2F;&#x2F;gist.github.com&#x2F;pathikrit&#x2F;a7845f72645159646fdb632bc3...</a><p>Let C&lt;A&gt; be a higher-kinded type e.g. in List&lt;Animal&gt;, List is C and Animal is A.<p>Let S be a subtype of T e.g. in class Cat extends Animal, Cat is S and Animal is T<p>If C&lt;S&gt; is a subtype of C&lt;T&gt;, then C is covaraint on T e.g. List&lt;Cat&gt; is a subtype of List&lt;Animal&gt;<p>If C&lt;T&gt; is a subtype of C&lt;S&gt;, then C is contravariant on T e.g. Predicate&lt;Animal&gt; is a subtype of Predicate&lt;Cat&gt;<p>If neither C&lt;T&gt; and nor C&lt;S&gt; are subtypes of the other, thenC is invariant on T
asavinovalmost 8 years ago
Covariance can be thought of as a mechanism for overriding functions. Assume there is a (base) function<p><pre><code> f: X -&gt; Y </code></pre> We want to override it by providing a new mapping from U to V:<p><pre><code> f: U -&gt; V </code></pre> This mechanism is said to be covariant if the new function guarantees that<p><pre><code> If u &lt;: x then v=f(u) &lt;: y=f(x) </code></pre> This means that for each more specific input u in U the function returns more specific (not more general) output v in V.
OJFordalmost 8 years ago
This post presents a nice example, but only for the particular type system envisaged by the author.<p>At least, I believe that the point of conceiving of &#x27;covariance&#x27; and &#x27;contravariance&#x27; is that we may have or not have either, in input or return types.<p>The submission presents one incarnation, a common one I believe, but nevertheless I think if the goal&#x27;s to understand variance, the concept must be distinguished from implementation.
评论 #14834770 未加载
bmc7505almost 8 years ago
This a topic that also comes up in linear algebra. Is there any analogy between vectors and types, or is the terminology just coincidental? <a href="https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;Covariance_and_contravariance_of_vectors" rel="nofollow">https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;Covariance_and_contravariance_...</a>
评论 #14834958 未加载
Patient0almost 8 years ago
Great article - I&#x27;m impressed that it covers every discovery I&#x27;ve painstakingly worked through over the years, all succinctly expressed on one page: Java arrays, immutable lists and even the fact that Eiffel got it wrong (which I remember puzzling over with a colleague back in the 90s)
rectangalmost 8 years ago
The difference between covariance and contravariance is enough to get UW professor Dan Grossman jumping up and down: <a href="https:&#x2F;&#x2F;www.youtube.com&#x2F;watch?v=pb_k8h6RuAY" rel="nofollow">https:&#x2F;&#x2F;www.youtube.com&#x2F;watch?v=pb_k8h6RuAY</a>
enriqutoalmost 8 years ago
In mathematics we call each of them &quot;invariance&quot;, if we do not want to sound too pedantic (or unless the distinction cannot be deduced easily from context)<p>I feel that the examples in math are easier to understand that in programming. For example:<p>- The integral of a function is invariant to additive changes of variable : \int f(a+x)dx = \int f(x)dx<p>- The mean of a distribution is contravariant to additive changes of variable : \int f(a+x)xdx = -a + \int f(x)xdx<p>- The mean of a distribution is covariant to shifts of the domain (same formula, because f(x-a) is a shift of size &quot;a&quot;)<p>- The variance of a distribution is invariant to additive changes of variable<p>etc.
评论 #14835444 未加载
caseymarquisalmost 8 years ago
Something you learn to work around when you start getting creative with generics.
elvongrayalmost 8 years ago
Was thinking of Tensor Analysis when I saw the title
tritiumalmost 8 years ago
This is typical technical jargon conflation in furtherance of interview pedantry. Please spare me.<p>Looking at the words superficially, their definitions are easily discerned:<p><pre><code> Covariance: changing together, with similarity. Contravariance: changing in opposition to one another. </code></pre> But, as part of strategic nerd signaling in interviews to parse what a candidate has been reading lately, you&#x27;ll encounter middle managers that will cull contending close-call applicants based on trivia like this. Similar technical jargon that isn&#x27;t what you think it might be, due to some seminal blog post include &quot;composition&quot; or &quot;isomorphic&quot; or perhaps most obviously, the simple-but-loaded term &quot;functional.&quot;<p>Try defining the word functional incorrectly during a technical interview and see what happens.
评论 #14834967 未加载
评论 #14835327 未加载
评论 #14835112 未加载