Search code examples
functional-programmingocamlmutable

Mutable Data in OCaml


I've created a mutable data structure in OCaml, however when I go to access it, it gives a weird error,

Here is my code

type vector = {a:float;b:float};;
type vec_store = {mutable seq:vector array;mutable size:int};;

let max_seq_length = ref 200;;

exception Out_of_bounds;;
exception Vec_store_full;;

let vec_mag {a=c;b=d} = sqrt( c**2.0 +. d**2.0);;


let make_vec_store() = 
    let vecarr = ref ((Array.create (!max_seq_length)) {a=0.0;b=0.0}) in
         {seq= !vecarr;size=0};;

When I do this in ocaml top-level

let x = make _ vec _store;;

and then try to do x.size I get this error

Error: This expression has type unit -> vec_store
       but an expression was expected of type vec_store

Whats seems to be the problem? I cant see why this would not work.

Thanks, Faisal


Solution

  • make_vec_store is a function. When you say let x = make_vec_store, you are setting x to be that function, just like if you'd written let x = 1, that would make x the number 1. What you want is the result of calling that function. According to make_vec_store's definition, it takes () (also known as "unit") as an argument, so you would write let x = make_vec_store ().