Browse thread
When is a function polymorphic?
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Jacques Garrigue <garrigue@m...> |
| Subject: | Re: [Caml-list] When is a function polymorphic? |
From: Yaron Minsky <yminsky@gmail.com> > 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? The effect you are looking for does depend on the "as" notation. Here is how to write it: function A _ -> A () | (B _ | C _ | ... | ZZ _) as x -> x Note that the exhaustivity checker will correctly detect that you second case is complete, and the pattern-matching compiler will just branch on wheter the tag is A or not. I.e. no code will be produced to check the second pattern. As others pointed, polymorphic variants allow you to write it in a shorter way, because you can define a type abbreviation for the remaining cases, but in the end it uses the same "as" mechanism. Jacques Garrigue