Initialize an array for an empty custom OCAML type

ive configure your own data type

type vector = {a:float;b:float}; 

and I want to initialize an array of type vector, but not contain anything, just an empty array of length x.

following

 let vecarr = Array.create !max_seq_length {a=0.0;b=0.0} 

makes the init array equal to {a = 0; b = 0} and leaving this as empty gives me errors. Is what I'm trying to do is even possible?

+4
source share
3 answers

In OCaml, there cannot be an uninitialized array. But look at it like this: you will never have a hard error in your program caused by uninitialized values.

If the values ​​that you ultimately want to place in your array are not yet available, are you probably creating the array too soon? Consider using Array.init to create it at the moment the necessary inputs are available, without creating it earlier and leaving it temporarily uninitialized.

The Array.init function takes an argument as a function that it uses to calculate the initial value of each cell.

+6
source

How do you have nothing? When you retrieve an element of a newly initialized array, you have to get something, right? What do you expect to receive?

If you want to express the ability of a value to be invalid or some value of some type, you can use the option type, whose values ​​are either None or Some value :

 let vecarr : vector option array = Array.create !max_seq_length None match vecarr.(42) with None -> doSomething | Some x -> doSomethingElse 
+6
source

You can also initialize the "array using an empty array, ie [||]. Execution:

 let a = [||];; 

has the meaning:

 val a : 'a array = [||] 

to which you can add. It has a length of 0, so you cannot set anything, but for academic purposes this can be useful.

+3
source

All Articles