I would like to create a closure that creates an array if it has none,
or returns it, otherwise.
In common lisp the idiom is:
(let ((a nil))
(defun get-array ()
(cond ((null a)
(setf a (make-array 10 :initial-element 0)))
(t a))))
How do I achieve the same effect in OCaml?
I guess 'a' must be a reference to an array so I can change its
contents. Moreover I made it an optional type, since initially, the
array doesn't exist.
I tried the following with no success:
let get_array =
let a = None in
let get_array () =
match a with
None -> (a:= Some (Array.make 10 0);
!a)
| Some a -> !a in
get_array;;
Characters 88-89:
None -> (a:= Some (Array.make 10 0);
^
This expression has type 'a option but is here used with type 'b ref
.