resize - OCaml: Dynamic Arrays? -
i've been trying figure out how resize initialized array in ocaml. however, seems while can write function create brand new array elements of old 1 copied on (and slots), function's output cannot assigned existing array. how 1 this? there easy way in use references make happen if not without?
here's tiny example:
let rec function_that_adds_to_array storage args ... = (* let's function has set of if-else constructs controls does, , let's further 1 of cases leads to: *) let new_array = array.make (array.length storage) ("null", ("null", -2)) in array.blit collection 0 new_array 0 index; (* index controlled function's recursion *) array.set new_array index (obj_name, obj_expr); new_array) (* insert macro @ tail *) ... ;; ### main method ### let storage = array.make 10 ((x : string), (a, b)) in ... while true ... storage = function_that_adds_to_array storage args....; ...
a print statement @ end of function_that_adds_to_array(...) confirms new array returned, containing old elements of initial array, however, in main method, storage remains identical. because of immutability of ocaml's elements? thought arrays mutable. i've looked around, , mention writing hacks getting ocaml act perl, however, using 1 individual's resize hack function proved futile. way can storage become new array? needs update-able collection of tuples (i.e. (string, (x, y)) )?
in ocaml can't assign variables, period. there's no special limitation arrays. however, can have variable bound reference, can hold different values of same type. structure called "variable" in imperative languages. have different sized arrays in variable x
write code follows:
# let x = ref [| 0 |];; val x : int array ref = {contents = [|0|]} # array.length x;; error: expression has type int array ref expression expected of type 'a array # array.length !x;; - : int = 1 # x := [| 2; 3 |];; - : unit = () # array.length !x;; - : int = 2
the !
operator dereferences reference, , :=
operator assigns new value.
if you're new ocaml i'll include standard advice should investigate use of immutable data before deciding recreate patterns of imperative languages know. if you're not new ocaml, apologize impertinence!
Comments
Post a Comment