Anonymous Object Subtyping

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

Anonymous Object Subtyping

Jordo Odroj
I've had problems getting anonymous object subtyping to work using
type inference. There are some parts of it that I'd like to get worked
out in the long term (invarariant subtyping on anonymous containers),
but this example seems easier to deal with and decide what is wrong
(if anything) - it's quite simple:

typedef TwoFields = {
        x: Int,
        y: Int
}
typedef ThreeFields = {
        x: Int,
        y: Int,
        z: Int
}

// Dummy function just returns a new TwoFields, ignore param
function makeTwo(ignoreThis: TwoFields) : TwoFields{
        var twoRet : TwoFields = {x:2, y: 9, thirdField:'someThird'};   // Fail here
        return twoRet;
}


// Example A
makeTwo({x:1,y:8,z:9})  // Fails but I can understand why it does so.
I might have accidentally put a z field.

// Example B
var twoWithExtra: TwoFields = {x:9,y:9,z:876};   // Fail here
makeTwo(threePassIn);
               
// Example C
var threeProper : ThreeFields = {x:9, y: 8, z: 98};  // Succeeds.
makeTwo(threeProper);
               
Example A and B are basically the same thing. Example C is your
solution that you've proposed to me in the past.
The only thing.. Is that it requires me to have to create a new type
called ThreeFields, or make an "extension" var threePropper :
{>TwoFields, z:Int}.
If I have many additional fields, it could get a little cumbersome.

Nicolas,
I understand why you chose to prevent example A from passing the type
checker. The user *clearly* entered an extra field. But not in example
B.
In fact, in the future I'd even like example A to pass the type
checker, as users might want extra fields that the required fields
call back into (more on that later).
I think in the mean time I just have to annotate extensions everywhere
in my code.
Would you consider rethinking this? What is the absolute best solution?


Jordo

--
haXe - an open source web programming language
http://haxe.org