caml-list - the Caml user's mailing list
 help / color / mirror / Atom feed
* [Caml-list] GADT magic
@ 2015-10-03  7:02 Rodolphe Lepigre
  2015-10-03  8:54 ` Gabriel Scherer
  0 siblings, 1 reply; 3+ messages in thread
From: Rodolphe Lepigre @ 2015-10-03  7:02 UTC (permalink / raw)
  To: Caml List

Dear list,

I am using a GADT and some phantom types to implement an abstract syntax
tree for some functional programming language, say the λ-calculus.

My first type definition was something like:

==========
type valu =
  | LVar of string
  | LAbs of valu -> term
and  term =
  | Valu of valu
  | Appl of term * term
==========

This works fine, but it is annoying to work with because of the coercion
constructor "Valu". Then I decided to be to smarter and use some GADT and
phantom types:

==========
type v
type t

type _ expr =
  | LVar : string              -> 'a expr
  | LAbs : (v expr -> 'b expr) -> 'a expr
  | Appl : 'a expr * 'b expr   ->  t expr

type term = t expr
type valu = v expr
==========

This definition is much more convenient since the type "valu" is (kind of)
a subtype of the type "term". It is not a real subtype since I had to
define a function with the type:

==========
val expr_to_term : type a. a expr -> term
==========

This function is exactly the identity function, but for the type checker
to accept it I need to be quite explicit:

==========
let expr_to_term : type a. a expr -> term = function
  | LVar(x)   -> LVar(x)
  | LAbs(f)   -> LAbs(f)
  | Appl(t,u) -> Appl(t,u)
==========

Of course, a better and more efficient implementation for this function
is "Obj.magic", but this is not the question here. I was expecting the
following definition to work:

==========
let expr_to_term : type a. a expr -> term = function
  | LVar(x)   -> LVar(x)
  | LAbs(f)   -> LAbs(f)
  | t         -> t
==========

But it does not type check. This is weird because all remaining patterns
captured by the "t" have type "term"...

Is this normal behaviour? Is this a bug?

Rodolphe
-- 
Rodolphe Lepigre
LAMA, Université Savoie Mont Blanc, FRANCE
http://lama.univ-smb.fr/~lepigre/

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

end of thread, other threads:[~2015-10-05  1:27 UTC | newest]

Thread overview: 3+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2015-10-03  7:02 [Caml-list] GADT magic Rodolphe Lepigre
2015-10-03  8:54 ` Gabriel Scherer
2015-10-05  1:27   ` Jacques Garrigue

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).