Version française
Home     About     Download     Resources     Contact us    
Browse thread
When is a function polymorphic?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Martin Jambon <martin_jambon@e...>
Subject: Re: [Caml-list] When is a function polymorphic?
On Wed, 30 Mar 2005, Yaron Minsky wrote:

> I think I screwed up the original examples a bit.  I think the effect
> I'm looking at doesn't depend on the "as" notation in particular.
> Here's another example that doesn't use "as":
>
> # function Some x -> Some () | None -> None;;
> - : 'a option -> unit option = <fun>
> # function Some x -> Some () | x -> x;;
> - : unit option -> unit option = <fun>
>
> The reason I want this is for the following example.  Consider some
> complicated union type with a single parameter:
>
> type 'a foo = A of 'a | B of int | C of string * string | ... | ZZ of float
>
> I want a function that converts an 'a foo to a unit foo.  I tried to
> write it this way:
>
> function A _ -> A () | x -> x
>
> But this ends up having type: unit foo -> unit foo, which isn't what I
> want at all.  Any idea of how to achieve this cleanly?

With polymorphic variants, you can do something like this:

# type const = [ `B of int
               | `C ];;
  type const = [ `B of int | `C ]

# type 'a poly =
    [ `A of 'a
    | const ];;
    type 'a poly = [ `A of 'a | `B of int | `C ]

# let f : 'a poly -> unit poly= function
    `A _ -> `A ()
  | #const as x -> x;;
    val f : 'a poly -> unit poly = <fun>



Martin

--
Martin Jambon, PhD
http://martin.jambon.free.fr