Browse thread
[Caml-list] Fwd: Polymorphic optional label argument, with default
[
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: | Gerd Stolpmann <info@g...> |
| Subject: | Re: [Caml-list] Fwd: Polymorphic optional label argument, with default |
On Sam, 2004-04-10 at 23:36, Richard Jones wrote:
> Hi:
>
> I posted the message below originally on ocaml_beginners. There were
> many helpful responses, and the general consensus was that this was
> not possible, but no one could give a definitive answer. I just
> wanted to confirm on the 'grown-ups' list (:-) if this is really true
> before I finalise the API I am designing.
>
> Thanks,
>
> Rich.
>
> To: ocaml_beginners@yahoogroups.com
> From: Richard Jones <rich@annexia.org>
> Subject: Polymorphic optional label argument, with default
>
> I have a function defined:
>
> let plot ?(labels = string_of_int) graph =
> (* ... *)
>
> The idea of the optional 'labels' argument is to specify a polymorphic
> function 'a -> string which is used to print labels stored in the
> 'graph' argument.
>
> The problem is that because string_of_int is obviously int -> string,
> my function is typed as:
>
> plot : ?labels : (int -> string) -> (* ... int ... *) -> unit
>
> but I want it to be typed as:
>
> plot : ?labels : ('a -> string) -> (* ... 'a ... *) -> unit
>
> [The 'a types are the same type. If I leave out the initializer, then
> it works.]
>
> How to?
This does not work. If "plot" were not specialised to int labels, you
could call
plot string_graph
(i.e. without ~labels), and where string_graph would be another
specialisation to string labels. This is unsound, because you would
apply string_of_int to strings.
One way out is the two function solution already discussed in
ocaml-beginners (i.e. having "plot" for the polymorphic case, and
"plot_int" for the int case).
Another idea is to store the default for "labels" in the graph. (Or to
implement the graphs with classes, which is a similar approach, but more
effective when you have several such defaults.)
I suppose there is also a good solution with extensional polymorphism,
but this isn't yet in mainstream O'Caml.
Gerd
--
------------------------------------------------------------
Gerd Stolpmann * Viktoriastr. 45 * 64293 Darmstadt * Germany
gerd@gerd-stolpmann.de http://www.gerd-stolpmann.de
------------------------------------------------------------
-------------------
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