Previous Contents Next


Classes and Modules for Data Structures

We wish to construct class hierarchies based on the application of functors for classical data structures.

We define the following structures

# module type ELEMENT =
class element :
string ->
method to_string : unit -> string
method of_string : string -> unit
end ;;

# module type STRUCTURE =
class ['a] structure :
method add : 'a -> unit
method del : 'a -> unit
method mem : 'a -> bool
method get : unit -> 'a
method all : unit -> 'a list
method iter : ('a -> unit) -> unit
end ;;
  1. Write a module with 2 parameters M1 and M2 of types ELEMENT and STRUCTURE, constructing a sub-class of ['a] structure in which 'a is constrained to M1.element.

  2. Write a simple module Integer which respects the signature ELEMENT.

  3. Write a simple moduleStack which respects the signature STRUCTURE.

  4. Apply the functor to its two parameters.

  5. Modify the functor by adding the methods to_string and of_string.

  6. Apply the functor again , and then apply it to the result .

Abstract Types

Continuing from the previous exercise, we wish to implement a module with signature ELEMENT of which the class element uses one instance variable of abstract type.

We define the following parameterized type:

# type 'a t = {mutable x : 'a t; f : 'a t -> unit};;

  1. Write the functions apply, from_string and to_string. These last two functions will use the Marshal module.

  2. Write a signature S which corresponds to the signature previously inferred by abstracting the type t.

  3. Write a functor which takes a parameter with signature S and returns a module of which the signature is compatible with ELEMENT.

  4. Use the resulting module as the parameter of the module from the previous exercise.

Previous Contents Next