Questions tagged [covariance]

Covariance, contravariance and invariance describe how the existing type inheritance hierarchy changes when subjected to some transformation (such as usage within generics). If the transformation keeps the ordering of the original hierarchy, it is "covariant". If it reverses it, it is "contravariant". If it breaks it, it is "invariant".

About Type Ordering

Let's say that a class P (parent) is inherited by a class C (child).

We can denote this fact as: P > C.

Informally, P is "larger" than C since it "contains" all the possible instances of C, but can also contain some other instances that are not C. Child is always parent but not necessarily the other way around.

Variance in Generics

Let's say that there is a generic type G that has a single generic parameter T, denoted by: G{T}.

  • If G{P} > G{C}, then T is co-variant (it preserves the original inheritance ordering).
  • If G{P} < G{C}, then T is contra-variant (it reverses the original inheritance ordering).
  • If G{P} and G{C} are type-unrelated, then T is invariant (it "breaks" the inheritance).

So the variance is the property of transformation (in this case: generic parameter T of G), not the original type hierarchy (P and C).

C# Examples

The generic parameter T of IEnumerable<out T> is covariant (as denoted by "out" keyword), meaning you can "forget" that the collection contains Cs and just treat it as if it contains Ps. For example:

IEnumerable<C> ec = ...;
IEnumerable<P> ep = ec;

The generic parameter T of Action<in T> is contravariant (as denoted by "in" keyword), meaning that an action that accepts P can also accept C. For example:

Action<P> ap = ...;
Action<C> ac = ap;

The generic parameter T is contravariant and generic parameter TResult is covariant in Func<in T, out TResult>. Each generic parameter is considered a different "transformation" with its own variance. This lets you write a code like this:

Func<P, C> fpc = ...;
Func<C, P> fcp = fpc;

And finally, the generic parameter T of IList<T> is considered invariant, so IList<P> and IList<C> are considered unrelated types (there is no assignment compatibility in either direction).


Tag usage

  • Do not use for the measurement of the strength and direction of the linear relationship between two random variables (statistical context). Instead, use other related tags, for example, .
    Moreover, consider whether the question might be better suited to Cross Validated, the Stack Exchange site for statistics, machine learning and data analysis.
1905 questions
0
votes
0 answers

Scala Covariance confusion

I am getting the following error: else if(x > elem) new NonEmpty(x, left, right insert x) I changed the covariance to contravariance type but didnt work object TestTree extends App { val t1 = new NonEmpty(100, new Empty, new Empty) …
0
votes
3 answers

Covariant function parameter in Kotlin

I want to implement a function that optionally takes an Activity class and redirects to it. If no class is provided, a default will be used. In Java I'd do public void onComplete(@Nullable Class redirectTarget) { if…
Marcel Bro
  • 4,907
  • 4
  • 43
  • 70
0
votes
0 answers

I want to put factor scores of different indicators in a data frame for factor score path analysis

I am doing factor score path analysis I am doing factor score path analysis for a latent variable and so I did factor score analysis to generate factor scores. Now I want to generate a variance-covariance matrix so I want to put the factor scores I…
0
votes
1 answer

C# interface covariance, specify parameter type

I've been trying to work out how to get an equivalent of the following Java code in C# (Command is a functional interface). public interface Executor { void execute(final C command) throws Exception; } The way my code is…
J Lewis
  • 462
  • 1
  • 4
  • 15
0
votes
0 answers

Why List is allowed but List is not in following code?
I have been playing with generics and variance. I have two lists one without generics and with generics defined like below: List l1 = new ArrayList(); List l2 = new ArrayList(); The compiler works fine for first. But for…
krupal.agile
  • 735
  • 8
  • 22
0
votes
1 answer

Using coeftest results in predict.lm()

I am analyzing a dataset in which the variance of the error term in the regression is not constant for all observations. For this, I re-built the model, estimating heteroskedasticity-robust (Huber-White) standard errors using the coeftest function.…
0
votes
0 answers

Converting/Cast to SuperType Variance

I have the following: public class MyExample : IMyExample { public string Property1 {get; set;} public string Property2 {get; set; } public class MySubType : IMySubType, MyExample { public List ExtraProperty {get; set;} } public…
The_Chud
  • 991
  • 1
  • 11
  • 24
0
votes
0 answers

How Can I implement covariance of training samples by Python?

I want to implement the covariance of training samples, which can be used when calculating the Mahalanobis distance. How can I implement this equation in Python? I referenced that image in 'A Simple Unified Framework for…
모하니
  • 11
  • 3
0
votes
2 answers

Applying PCA to a covariance matrix

I am have some difficulty understanding some steps in a procedure. They take coordinate data, find the covariance matrix, apply PCA, then extract the standard deviation from the square root of each eigenvalue in short. I am trying to re-produce this…
Jack Armstrong
  • 1,182
  • 4
  • 26
  • 59
0
votes
3 answers

How to calculate covariance matrix of data frame

I have read data frame of sensor data, using pandas read_fwf function. I need to find covariance matrix of read 928991 x 8 matrix. Eventually, I want to find eigen vectors and eigen values, using principal component analysis algorithm for this…
YatShan
  • 425
  • 2
  • 8
  • 22
0
votes
2 answers

Why doesn't EmpiricalCovariance output a matrix with a constant diagonal?

When using EmpiricalCovariance to develop a covariance matrix for high-dimensional data, I would expect the diagonal of this matrix (from the top-left to the bottom-right) to be all ones, as of course a variable is always going to perfectly…
Ian
  • 5,704
  • 6
  • 40
  • 72
0
votes
2 answers

Use super method with sub type param

I'm trying to implement some function in a super class so I don't have to always repeat it in its children. Sample: trait Animal { def applyF(transition: Animal => Animal): Animal = transition(this) // Animal as param and return type } case class…
Piu130
  • 1,288
  • 3
  • 16
  • 28
0
votes
3 answers

Can't get co/contra-variance to work in C#

abstract class A { List Items { get; set; } } class B {} class C : A {} class D : B {} class E : A {} static class X { public A GetThing(bool f) { return f ? new E() : new C(); } } Type of conditional expression cannot…
enashnash
  • 1,578
  • 1
  • 15
  • 36
0
votes
1 answer

How to use cov function to a dataset iris python

I want to get the covariance from the iris data set, https://www.kaggle.com/jchen2186/machine-learning-with-iris-dataset/data I am using numpy, and the function -> np.cov(iris) with open("Iris.csv") as iris: reader = csv.reader(iris) data =…
Mar
  • 3
  • 2
0
votes
0 answers

Create matrix3 from: constant * matrix1 + (1-constant) * matrix 2

I need help creating a matrix that corresponds to this equation: c * matrix1 + (1-c) * matrix2 Where matrix1 is given by: Function VarCovarZeros(InputMatix As Range) As Variant Dim MatrixColumns As Long MatrixColumns =…
Pernille
  • 23
  • 3
1 2 3
99
100