'OCaml: accessing a type in the Stdlib

I want to use the Stack module from the Stdlib of OCaml, but I also need a membership function, which the Stack module lacks. So, following https://dev.realworldocaml.org/files-modules-and-programs.html, I created a file stack1.ml reading:

include Stack
let mem a t = List.mem a t.c

since c is the name of the record used in stack.ml (that file contains the line: type 'a t = { mutable c : 'a list; mutable len : int; }). But I get:

Error: Unbound record field c

What can I do ? (And also: do I need a file with a different name Stack1 ? This is a bit annoying for the files calling it.)



Solution 1:[1]

The fact that the type 'a Stack.t is implemented using a mutable list or any other data type is an implementation detail that is abstracted away by the interface of the Stack module.

In other words, outside of the Stack module, you can only use the functions provided by the stack module that works on the abstract type 'a Stack.t independently of this implementation.

Fortunately, those functions are more than enough to implement a mem function. For instance, with a fold:

let mem x s = Stack.fold (fun acc y -> acc || x = y) false s

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 octachron