Poperton
Poperton

Reputation: 1806

How to do function override in OCaml?

I've read the entire chapter about modules on this book but there's something I didn't understand.

Suppose I have a signature and an implementation of that signature:

module type X = sig
  val x : int
  val y : int
end

module X1 : X = struct
  let x = 5;
  let y = 6;
end

Then suppose I have a functor that has this signature as paremeter:

module IncX (M: X) = struct
  let x = M.x + 1
end

What if I want to instantiate IncX using the already defined X1 module but override the y function?

I want to do something like this:

module X1_Specialized : X = struct
  //how use x from X1 module here?
  let y = 10;
end

The analog in OOP languages would be to override a function.

Upvotes: 1

Views: 717

Answers (1)

glennsl
glennsl

Reputation: 29146

What you ask for is usually called implementation inheritance. And it's not necessary to use a functor for this, just include:

module X1_Specialized : X = struct
  include X1
  let y = 10
end

include will include the entire contents of X1, as if you had written its definition in place of the include. This includes a definition of y, but the following definition of y will shadow it, and essentially replace it.

Also note that OCaml doesn't use semicolon as a statement terminator. These are syntax errors in your code.

Upvotes: 3

Related Questions