Its_Bryan Its_Bryan

Niner since 2011


  • E2E: Brian Beckman and Erik Meijer - Co/​Contravaria​nce in Physics and Programming, 3 of n

    I tried to come up with some comparable examples in code. We have already seen covariance in the shows, but I think what I believe is a contrvariant example is interesting because it has a pattern similar to the physics examples.


    // Here is a simple select to get the fuel spent

    fuelUsed = times.Select(ToLatLon).Select(FuelSpentAt); 

    // Now suppose the function we have the get the fuel spent needs XYZ

    // then we can compose FuelSpentAt with ToXYZ

    fuelUsed = times.Select(ToLatLon).Select(latLon => FuelSpentAt(ToXYZ(latLon))); 

    // Now if we separate the composition we see it is covariant (yes this was already covered)

    fuelUsed = times.Select(ToLatLon).Select(ToXYZ).Select(FuelSpentAt);

    // FuelSpentAt • ToXYZ • ToLatLon

    IEnumerable<XYZ> orderedXYZs;//IEnumerable<LatLon> orderedLatLon;

    // Now lets say we want to get the XYZs ordered by the rate that fuel was being  consumed at that point. This is pretty straight forward with a function that takes XYZ and returns a rate.

    orderedXYZs = times.Select(ToXYZ).OrderBy(FuelRateAt);

    // Suppose though we only have a FuelRateAt function that takes LatLon in this case we can compose ToLatLon with FuelRateAt inside the OrderBy

    orderedXYZs = times.Select(ToXYZ).OrderBy(xyz => FuelRateAt(ToLatLon(xyz)));

    // If we separate the composition we get the following.  Now I beliebe OrderBy is contravariant since IComparable is contravariant,  but I might be wrong. But the interesting thing is that this pattern is like the pattern Brian Beckman had in the physics example

    orderedXYZs = times.Select(ToXYZ).Select(ToLatLon).OrderBy(FuelRateAt).Select(ToXYZ);

    // ToXYZ • FuelRateAt • ToLatLon • ToXYZ

    // Note the inverse (ToXYZ) is composed to the left of the FuelRateAt function