Initialize Array to Blank custom type OCAML

坚强是说给别人听的谎言 提交于 2019-12-10 17:29:47

问题


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?


回答1:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/1591175/initialize-array-to-blank-custom-type-ocaml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!