Paste: implementing named unions in clay

Author: kssreeram
Mode: text
Date: Mon, 30 Aug 2010 17:17:22
Plain Text |


//
// NamedUnion
//

record NamedUnion[...Fields] {
    data : Union[...mapValues(x => x.1, ...Fields)];
}

private fieldIndex(name, ...fields) {
    var i = 0;
    static for (field in ...fields) {
        if (name == field.0)
            return i;
        i += 1;
    }
    error("invalid field name");
    return -1;
}

[...fields]
overload fieldRef(x:NamedUnion[...fields], name) {
    alias i = fieldIndex(name, ...fields);
    return ref staticIndex(x.0, static i);
}




//
// sample code for named unions
//

alias MyUnion = NamedUnion[(#foo, Int), (#bar, UInt8)];

main() {
    var a = MyUnion();
    a.foo = -1;
    println(a.bar);   // prints 255
}

New Annotation

Summary:
Author:
Mode:
Body: