lazypair again
May. 14th, 2010 10:31 amLast night I've managed to write a class
Then I started thinking about variance. It is positive on
So, whad do we have, given
So there's a question regarding an adequate categorical interpretation of caching in general. I kind of can't figure out, how to deal with it.
In my specific case, in my code, I'll be replacing
LazyPair
where x
is fixed and y
is lazily calculated, via a given function.Then I started thinking about variance. It is positive on
y
, but how about x
? It is not so for x
, since we have a function, and its argument should have negative variance. But I wrote in LazyPair
definition that it implements Product2
, that is, I'm saying it is "something like" a Cartesian product. So. If it is a Cartesian product, it should be covariant on both arguments.So, whad do we have, given
X
and YX
, and, of couse, we have X×YX → X×Y
- but it is not a natural transformation. In short, bad luck. No functoriality. So I probably have to throw away the idea of lazy pair.So there's a question regarding an adequate categorical interpretation of caching in general. I kind of can't figure out, how to deal with it.
In my specific case, in my code, I'll be replacing
LazyPair[X, Y] with (X, X=>Y) (this means X×YX
in Scala). But then thunk disappears. Something is wrong here.
Upd: thank you,
huzhepidarasa! Got this stuff working:
test("lazy pair should be covariant in first parameter") {
val p: Product2[Int, Int] = LazyPair(123, (x:Int) => x * x)
val q: Product2[Any, Int] = p
expect(123) {q._1}
}
test("lazy pair should be covariant in second parameter") {
val p: Product2[Int, Int] = LazyPair(8, (x:Int) => x * x)
val q: Product2[Int, Any] = p
expect(64) {q._2}
}
test("lazy pair assignment does not involve evaluation") {
var n = 0;
val p: Product2[Int, Int] = LazyPair(8, (x:Int) => {n = n + 1; x * x})
expect(0){n}
val q: Product2[Int, Any] = p
expect(0){n}
expect(64) {q._2}
expect(1){n}
}
(and thank you Martin for removing < from Scala!)