Struct in NXC and F#

172 Views Asked by At

I have a question:

There is such a struct function in NXC:

struct colorType
{
  int colorval;
  unsigned int rawRed;
  unsigned int rawGreen;
  unsigned int rawBlue;
  unsigned int normRed;
  unsigned int normGreen;
  unsigned int normBlue;
};

colorType cubeColor[6*9];

I have created the same struct in F# like this:

type colorType =
    struct 
        val colorval: int
        val rawRed: uint16
        val rawGreen: uint16
        val rawBlue: uint16 
        val normRed: uint16
        val normGreen: uint16
        val normBlue: uint16
    end

But I don't have any idea how to call colorType cubeColor[6*9]; in F#.

Could you help me for this case?

Thanks.

1

There are 1 best solutions below

0
On

As people said in the comments, technically, the answer is Array.zeroCreate (6*9), optionally followed by : colorType [] if the compiler cannot infer the type from context. This creates 54 instances of the structure, sequentially placed into an array.

However, you should be aware that:

  • The meaning of struct in the CLI (and thus F#) is very different from its meaning in C. I don't know NXC, but you should check the MSDN on structs to make sure this is what you want. In F#, struct signifies a value type, which is usually a performance optimization, but also alters semantics.

  • In F#, values are immutable by default, and colorType has no constructor, so all the values will remain zeroed and you will not be able to do anything useful with it until you add a constructor. Making the fields mutable instead will probably cause you headaches if the type remains a struct, because of the aforementioned changes in semantics. I would not recommend that.

  • While starting with a zeroed, mutable array is typical in many programming languages, it is only a sparsely used performance tool in F#. Usually, one would first start with an immutable list with actual data or other kinds of sequences and do mappings from the original data to new objects holding the desired result.

I would recommend to first do some tutorials or reading on F#, and get used to the language's typical tools. Topics like structs, explicit fields (val), and F#'s imperative tools might not be the best starting point.

There are many online resources for learning F#, for example tryfsharp.org, which even features a compiler for the samples if your browser is compatible.