Hacker News new | past | comments | ask | show | jobs | submit login

Nice system built with only a couple of C99 macros. That small header also achieves matching for specific C types over the "sum types".

In the context of C99, isn't tagged union the more usual name instead of sum type?




It's interesting but not very practical. It's an "algebra of types" with only constants, no variables, since C does not have type variables. Thus it misses much of the point of algebraic data types in a language like Haskell (deep composability and generics with very little code to write).

Take one of the most basic sum types in Haskell's base library, Maybe:

    data Maybe a = Nothing | Just a
This simple construction gives you the ability to write functions over optional values and avoid the issues with null pointers. This would be an amazing feature to have in C but it can't be achieved due to C's very limited type system.


I used to define `Maybe` in C as a macro over a tagged union. It really unveiled a number of logic errors at compile-time, but the issue of course is to use this kind of metaprogramming sanely. E.g., instantiating `Maybe` to some other macro `T(a)`, where `a` is some other (concrete) type, would already cause a headache.


I got to say adding type variables to C would be super duper. And to me actually feels rather C like as well.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: