4

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?

Faisal Abid
  • 8,900
  • 14
  • 59
  • 91
  • What is wrong with your example? It seems perfectly reasonable to me. I guess some _intention_ or _perspective_ on _why_ this is _bad_ would be helpful. But this is usually how it's done, that or using 'a option types. _emphasis_. – nlucaroni Oct 19 '09 at 22:07

3 Answers3

6

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
newacct
  • 119,665
  • 29
  • 163
  • 224
6

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.

Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
4

You can initialize and 'a array by using an empty array, i.e., [||]. Executing:

let a = [||];;

evaluates to:

val a : 'a array = [||]

which you can then append to. It has length 0, so you can't set anything, but for academic purposes, this can be helpful.

profase
  • 41
  • 2