[Haskell-cafe] Haskell integration with C/C++ (GSOC)

Brandon Allbery allbery.b at gmail.com
Thu Apr 5 08:42:42 CEST 2012


On Thu, Apr 5, 2012 at 01:53, Sutherland, Julian <
julian.sutherland10 at imperial.ac.uk> wrote:

> data Tree = Node Left Right | Leaf
>
> Could be converted to a struct in C/C++:
>
> struct Tree {
>     struct Tree* left;
>     struct Tree* right;
> };
>

Shouldn't this actually be a tagged union?  Not that they exist as such in
C/C++, but are easy enough to emulate (minus the extra type checking that
real tagged unions such as even Pascal gives you):

    struct Tree {
      enum {Node, Leaf} tag;
      /* possibly tag sanity checking macros defined here */
      union {
        struct {
          struct Tree *tree_Node_left;
    #ifdef HSC_CHECKED
    #  define tree_left(tree) (tree->tag == Leaf ? _hsc_abort("tree:
Node.left of Leaf") : tree->_tree_Node.tree_Node_left)
    #else
    #  define tree_left(tree) tree->_tree_Node.tree_Node_left
    #endif
          struct Tree *tree_Node_right;
    #ifdef HSC_CHECKED
    #  define tree_right(tree) (tree->tag == Leaf ? _hsc_abort("tree:
Node.right of Leaf") : tree->_tree_Node.tree_Node_right)
    #else
    #  define tree_right(tree) tree->_tree_Node.tree_Node_right
    #endif
        } _tree_Node;
        /* strictly we can collapse out the union here because Leaf has no
data */
      } _tree_data;

Similarly several of your other examples could use a bit more thought.

-- 
brandon s allbery                                      allbery.b at gmail.com
wandering unix systems administrator (available)     (412) 475-9364 vm/sms
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20120405/74aef389/attachment.htm>


More information about the Haskell-Cafe mailing list