Dear OCaml community,
I am a computer science teacher and, while teaching OCaml programming, I use types for abstract data structures.
For example :
type 'a stack = { (* abstract imperative stack *)
empty : unit -> bool;
push : 'a -> unit;
pop : unit -> 'a
};;
A value of type stack must therefore implement those 3 functions.
Then, to create a stack implemented by an array :
let stack_of_array t = (* t is the array that will contain stack elements *)
let n = ref 0 in {
empty = (fun () -> !n = 0);
push = (fun e -> if !n >= Array.length t
then failwith "Full stack"
else (t.(!n) <- e; incr n);
pop = (fun () -> if !n = 0
then failwith "Empty stack"
else (decr n; t.(!n)))
}
let s = stack_of_array (Array.make 100 0) in (* example *)
s.push 4;
s.pop ()
I like this style because of the encapsulation, the OOP style, the ability to design algorithms working with any stack implementation. However, I never saw something like this anywhere and I wonder why.
My question is: I am doing it right ? Would it be considered a better practice using modules and functors (I don’t see why that would be more convenient though) ?