English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    
Browse thread
[Caml-list] Exceptions as datatypes
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Patrick M Doane <patrick@w...>
Subject: [Caml-list] Exceptions as datatypes
It seems possible to use exceptions as datatypes with some
(potentially useful) changes to the typing discipline. For example:

module M1 = struct
  type t = Int of int | Float of float
  let to_string = function
  | Int n -> string_of_int n
  | Float f -> string_of_float f
end

module M2 = struct
  exception Int of int
  exception Float of float
  let to_string = function
  | Int n -> string_of_int n
  | Float f -> string_of_float f
  | _ -> "<unknown>"
end

let test () =
  print_endline (M1.to_string (M1.Int 5));
  print_endline (M2.to_string (M2.Int 5));

Since the 'exn' type is not polymoprhic, there are no concerns about a
top-level structure failing to generalize a type variable.  It's also
extensible:  For example, a syntax tree could include annotations without
changing its type:

type t =
  | Int of int
  | Binary of op * t * t
  | Annotation of exn
  | ...

For most applications, the traditional or polymorphic variants work fine -
but I can think of several examples where these exception datatypes could
be extremely useful.

Looking at the assembly output, it appears that the the matching is linear
with two memory reads per comparison.  I think that the code generation
for exception matching can be improved though.  Is the following
strategy sound?

Each module reserves a chunk of memory in its data section of the same
size as the number of exceptions declared.  Whenever an exception is
created, it would include a pointer into that chunk (with an offset based
on its ordering in the file).  Pattern matching on exception values
subtracts that pointer from the head of the chunk and then use a
logarithmic search or jump table depending on the number of cases.  If the
pattern matching was performed on exception values from more than one
module, then the subtraction (and subsequent comparisons) is done for each
module.

-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners