Create Sum Type in C-Implementation of OCaml Function

Say you had an ad like:

type foo = Bar | Baz of int

How would you implement the C function to create a base? Say I declare the following:

external create_baz : int -> foo = "create_baz"

Then I will need to fill in this code:

CAMLprim value create_baz(value bar) {
  // what do I do here?
}

I understand that this is pretty stupid, but it's just an example of what I'm trying to do.

+4
source share
1 answer

This is described in chapter 19 of the OCaml manual .

, . (, , Bar) , , (, Baz), . 0.

( , int). , , , , .

, 1 0. Bar 0- ( ).

:

value create_baz(value bar) {
    // Caller guarantees that bar is an int.
    //
    CAMLparam1(bar);
    CAMLlocal1(result);
    result = caml_alloc(1, 0);
    Store_field(result, 0, bar);
    CAMLreturn(result);
}
+3
source

Source: https://habr.com/ru/post/1539351/


All Articles