Datatype99: C99 with Sum Types, v0.1.0
github.com
github.com
void copy(BinaryTree *dest, const BinaryTree *src) {
match(*src) {
of(Leaf, x) {
*dest = TREE(Leaf(x));
}
}
}
then realised that this still points to a leaf on the stack. Need a way to replace all the pointers to be relative to the destination tree...Personally I have a much easier time dealing with tree/graph data structures using indices, regardless of the language I'm using. Using indices as handles in general are just so much easier than using pointers in terms of memory management, and generally performs much better in terms of cache coherency. Indices are also easier to serialize/deserialize, and sometimes it just "makes sense" (for example, if you're developing a physics simulation, representing objects as indices are natural because you're going to use those index values inside various math equations.)
The downside might be that if you're creating and destroying nodes in a tree continuously. then you have to be careful about reusing indices. There's a pattern in gamedev (generational indices) that solve the issue (basically, in addition to an index you also store a counter value with it, and you increment the counter everytime you allocate a new node in the same spot of the array. It's a bit more bookkeeping, but there's lots of code examples for it. It's kind of a well-known trick inside gamedev (and recently in the Rust community, in order to bypass borrow checker issues).
A few pointers:
- https://floooh.github.io/2018/06/17/handles-vs-pointers.html
- https://kyren.github.io/2018/09/14/rustconf-talk.html
- https://news.ycombinator.com/item?id=17995634 (steveklabnik explaining how generational indices work with code).
I would suggest recursively walking through the original tree, creating an equivalent tree in the process instead of copying the original elements.
/* get size required for malloc */
size_t getsize(const BinaryTree *tree) {
size_t acc = sizeof(*tree);
match(*tree) {
of(Leaf, x) {
return acc;
}
of(Node, lhs, x, rhs) {
return getsize(*lhs) + acc + getsize(*rhs);
}
}
}
BinaryTree* copy(BinaryTree *dest, const BinaryTree *src) {
dest->tag = src->tag;
match(*src) {
of(Leaf, x) {
*dest = Leaf(*x);
}
of(Node, lx, x, rx) {
match(*dest) {
of(Node, ly, y, ry) {
*ly = dest + 1;
*ry = copy(*ly, *lx);
*y = *x;
copy(*ry, *rx);
}
otherwise {}
}
}
}
return dest + 1;
}
Kind of hackish, but I guess it works. SUM(foo) {
foo_one,
foo_two,
};
/* declare each sum case */
CASE(foo, foo_one) { int i; char c; };
CASE(foo, foo_two) { double d; };
void do_bar(foo f) {
MATCH(f) {
AS(foo_one, y) printf("foo_one: %d, %c\n", y->i, y->c);
AS(foo_two, y) printf("foo_two: %d\n", y->d);
MATCHANY
fprintf(stderr, "No such case!");
exit(1);
}
}
[1] https://github.com/naasking/libsumIt's just baffling to me that tagged unions could be shunned in favour of the visitor pattern. How could that ever look like progress?
Being a millenial, I don't know what programming was like the 80's, but surely tagged unions must have been bread and butter for Pascal programmers?
In theory you can have both of course, and C++ now has support for variants (because we know C++ tries to be come a superset of all programming languages in existence). It's still a bit clunky to use though, especially because of the lack of "match" support in the language.
But I think a problem is that it's easy to mess up tagged union in low level, non-managed languages. Rust's enum work great, but that's thanks to the very strong type system and borrow checker which makes them effectively impossible to mess up in safe code.
In C or C++ it can become messy and hard to debug. In C you don't really have a choice, so you do it anyway but in C++ virtual methods and inheritance are usually a bit easier to manage.
struct my_tagged_union {
enum my_tag_enum tag;
union {
....
} payload;
};
That would be a pretty big break with "tradition" for the C language ;) (e.g. it would be similar to a "builtin string type")And of course tagged unions as "generic user-defined types" are much less convenient/useful than being directly integrated into the language syntax and type system.
Coincidentally, even padding bytes break things technically. Since they're undefined, you - in theory - can't ever calculate a bytewise hash value over a struct that has any padding bytes. It's still done frequently, it's just nulled out beforehand and copying is bytewise anyway. Doesn't change the fact that to the spec letter it's undefined behaviour. GCC also added __builtin_clear_padding() recently.
Hidden tags ... no. Just no.
From a modern perspective, it may be difficult to understand just how crushing the OO consensus was in the 1980s and 1990s. It still reverberates in our language design today. OO was good design was OO. If it didn't fit into OO, that was ipso facto proof that it was bad. Close the book. No further evidence required. Sum types? Kinda overlaps inheritance. Bad design. Not OO, therefore bad design. Why is Java a better language than C++? It's more OO, so QED.
OO here, by the way, is specifically that variant that emerged in the form of C++ and Java. Very important to have defined, enforced "private" keywords and deep hierarchies. Smalltalk by this definition is not an OO language. (And also, therefore, bad. Also possibly heretical for trying to steal the term OO... and I mean all the implications of the word "heretical".)
My "Software Engineering" course circa 1999 was basically "How to Design Software via OO". (It has the distinction of being the one course from my entire college career that I'm not sure I agree with a single thing I "learned" in that course. Even at the time I had done enough real work to be suspicious, and from here in 2021 I find the whole thing risible. But I got a 4.0, so....) Formal diagrams with strictly enforced diagram languages like UML, because OO was the future of Good Design and UML was how OO was going to help bring programming to the masses who would only have to draw Object Hierarchies and then {magic goes here that never was worked out} and perfect programs!
The internet hit programmers and programming earliest, and now there's only a remnant of the OO dogma just hanging on by its teeth in school curricula that haven't hardly been changed in 25 years, and it lacks the power to envelop the students the way it used to.
There was of course always a counterculture that didn't listen, which is where you get Smalltalk, Perl, Haskell and its ancestry, Python, etc. But you have to bear in mind that that was a counterculture...
... and you know, even today, Java and C++ are still pretty darned popular and it's not that hard to find people who still only know one of those (or maybe both) and still think OO ≡ good design ≡ OO, and the vast chaotic landscape of languages that don't even have "private" is just kid stuff for people who can't handle Real Design. Which is OO. Because OO is good, and good is OO.
I assume pattern matching must be exhaustive. Can there be a default case?
Doesn't happen, apparently.
edit: For a short while libc++ adopted mpark's variant visit, which AFAIK compiles down to switch case with some hand coding. AFAIK it had other problems so they rolled back to the constexpr array of function pointers.
I don’t think they can inline foo as you’ve written it because the variant could be valueless by exception.
Sweet. C seems to be getting there :)
That Poica can't work on C99 made it a non-starter for me; but all I really wanted was the sum types.
https://ziglang.org/documentation/master/#Tagged-union
You create two types, a tag enum, and the tagged union itself, which has a typed "payload" for each tag.
Plus the necessary "syntax sugar" for initialization and extracting the payload by tag.
If it is possible to automatically generate these, could you provide an example?
About type_name: you can deduce a type name if you know at least one tag of a sum type. For example, if a tag is `Foo`, then `FooSumT` is a typedef to an outer sum type (datatype99 generates this typedef).
If you can force the types to contain a member of the same type (say, a int or enum foobar_discriminant), the pointers &const_var_foo.disc and &const_var_bar.disc would have to differ for obvious reasons.
#include <datatype99.h>
datatype(
BinaryTree,
(Leaf, int),
(Node, struct BinaryTree *, int, struct BinaryTree *)
);
What kind of preprocessor black magic can you do so that this code compiles? I don't dare to open the file datatype99.h lest it casts a dark spell on me.That sentence is everything I was taught to avoid. Props to you.
I like the drug/alcohol metaphor for these things, as a child avoid them, as an adult do your thing as long as you remain sensible.
But in most countries they would be able to drink (especially in a private setting), just not purchase. In Europe for instance less than half a dozen countries have a minimum drinking age for private settings, and a dozen more have an MDA in public (but not private), though for some 16 is enough to drink fermented alcohols (alongside a meal with adults for the UK, regardless for Germany and Austria).
This is absurd, but in a good way.
According to the GitHub, which appears to be a metaprogramming library by the same author.
By the way, it doesn't need to be Rust, there are plenty of alternatives, some of them like NEWP and PL/I variants are about 10 years older than C.
- langage actually uses safety features in api design (good luck updating libc to use this)
And sure enough, the code is unreadable and unmaintainable as you'd expect.
You can build Boost out of C99 macros. There's a really good reason why you shouldn't.