Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize Array to Blank custom type OCAML

Tags:

arrays

ocaml

ive set up a custom data type

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

and i want to Initialize an array of type vector but containing nothing, just an empty array of length x.

the following

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

makes the array init to {a=0;b=0} , and leaving that as blank gives me errors. Is what im trying to do even possible?

like image 658
Faisal Abid Avatar asked Dec 06 '22 04:12

Faisal Abid


2 Answers

You can not have an uninitialized array in OCaml. But look at it this way: you will never have a hard-to-reproduce bug in your program caused by uninitialized values.

If the values you eventually want to place in your array are not available yet, maybe you are creating the array too early? Consider using Array.init to create it at the exact moment the necessary inputs are available, without having to create it earlier and leaving it temporarily uninitialized.

The function Array.init takes in argument a function that it uses to compute the initial value of each cell.

like image 172
Pascal Cuoq Avatar answered Dec 14 '22 22:12

Pascal Cuoq


How can you have nothing? When you retrieve an element of the newly-initialized array, you must get something, right? What do you expect to get?

If you want to be able to express the ability of a value to be either invalid or some value of some type, then you could 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
like image 36
newacct Avatar answered Dec 14 '22 22:12

newacct