Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
Mapping phantom <-> non-phantom
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2008-07-07 (13:48)
From: Dario Teixeira <darioteixeira@y...>
Subject: Mapping phantom <-> non-phantom

Suppose you are using polymorphic variants as a phantom type to impose
certain restrictions on a data structure.  Is it possible in general to
formulate an equivalent structure that uses only regular variants, or is
the object system required for a full mapping?

As an example, consider the following structure constructed using phantom
types.  The "Text" and "Bold" nodes may appear anywhere in a document, but
the "Mref" and "See" nodes produce links, and links may not be the immediate
parents of other links:

module Phantom:
        type inline_t = node_t list
        and node_t =
                | Text of string
                | Bold of inline_t
                | Mref of string * inline_t
                | See of string

        type 'a t

        val text: string -> [> `Nonlink] t
        val bold: [< `Link | `Nonlink] t list -> [> `Nonlink] t
        val mref: string -> [< `Nonlink] t list -> [> `Link] t
        val see: string -> [> `Link] t
end =
        type inline_t = node_t list
        and node_t =
                | Text of string
                | Bold of inline_t
                | Mref of string * inline_t
                | See of string

        type 'a t = node_t

        let text txt = Text txt
        let bold inl = Bold inl
        let mref ref inl = Mref (ref, inl)
        let see ref = See ref

Though a bit contrived, the following structure expresses the same
restrictions using only conventional variants:

module Regular =
        type inline_t = super_node_t list
        and super_node_t =
                | Nonlink_node of nonlink_node_t
                | Link_node of link_node_t
        and nonlink_node_t =
                | Text of string
                | Bold of inline_t
        and link_node_t =
                | Mref of string * nonlink_node_t list
                | See of string

The version using PV-based phantom types doesn't require all this artifical
scaffolding, and is therefore preferable in my opinion.  However, the
ocamlyacc grammar for a document parser will naturally be closer to the
non-phantom version.  My doubt is therefore if one could devise a structure
using PV-based phantom types that becomes problematic to parse.

Thanks in advance for your time!
Kind regards,
Dario Teixeira

Not happy with your email address?.
Get the one you really want - millions of new email addresses available now at Yahoo!