English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    
Browse thread
Compiler feature - useful or not?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Edgar Friendly <thelema314@g...>
Subject: Compiler feature - useful or not?
When one writes

type row = int
type col = int

This allows one to use the type names "row" and "col" as synonyms of
int.  But it doesn't prevent one from using a value of type row in the
place of a value of type col.  OCaml allows us to enforce row as
distinct from int two ways:

1) Variants:
type row = Row of int
type col = Col of int

Downside: unnecessary boxing and tagging
conversion from row -> int: (fun r -> match r with Row i -> i)
conversion from int -> row: (fun i -> Row i)

2)  Functors:
module type RowCol =
sig
  type row
  val int_of_row : row -> int
  val row_of_int : int -> row
  type col
  val int_of_col : col -> int
  val col_of_int : int -> col
end

module Main = functor (RC: RowCol) -> struct
 (* REST OF PROGRAM HERE *)
end

Any code using rows and cols could be written to take a module as a
parameter, and because of the abstraction granted when doing so, type
safety is ensured.

Downside: functor overhead, misuse of functors, need to write
boilerplate conversion functions
conversion from row -> int, int -> row: provided by RowCol boilerplate

IS THE FOLLOWING POSSIBLE:
Modify the type system such that one can declare

type row = new int
type col = new int

Row and col would thus become distinct from int, and require explicit
casting/coercion (2 :> row).  There would be no runtime overhead for use
of these types, only bookkeeping overhead at compilation.

Downside: compiler changes (hopefully not too extensive)
conversion from row -> int: (fun r -> (r :> int)) (* might need (r : row
:> int) if it's not already inferred *)
conversion from int -> row: (fun i -> (i :> row))

Thoughts?  Do any of you use Variants or Functors to do this now?  Do
you find this style of typing useful?

E.