简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM