caml-list - the Caml user's mailing list
 help / color / mirror / Atom feed
* [Caml-list] Exceptions as datatypes
@ 2002-05-21 12:52 Patrick M Doane
  2002-05-22  2:59 ` Jacques Garrigue
  0 siblings, 1 reply; 3+ messages in thread
From: Patrick M Doane @ 2002-05-21 12:52 UTC (permalink / raw)
  To: caml-list

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


^ permalink raw reply	[flat|nested] 3+ messages in thread

end of thread, other threads:[~2002-05-22 11:57 UTC | newest]

Thread overview: 3+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2002-05-21 12:52 [Caml-list] Exceptions as datatypes Patrick M Doane
2002-05-22  2:59 ` Jacques Garrigue
2002-05-22 11:57   ` Patrick M Doane

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).