caml-list - the Caml user's mailing list
 help / color / mirror / Atom feed
* [Caml-list] issue with polymorphism
@ 2016-05-16 15:45 Guillaume Hennequin
  2016-05-16 15:57 ` Gabriel Scherer
  2016-05-16 15:57 ` Nicolas Ojeda Bar
  0 siblings, 2 replies; 9+ messages in thread
From: Guillaume Hennequin @ 2016-05-16 15:45 UTC (permalink / raw)
  To: caml-list

Dear caml-list,

let id x = x

is polymorphic, and indeed I can apply it to various types:

let _ = print_float (id 1.)
let _ = print_int (id 1)

Now, say you want to write a function that takes a function of the same ['a->'a] 
type as [id] above, and applies it to two different types:

let print_both f =
  print_int (f 1);
  print_float (f 1.0)

That in fact won't compile:

Error: This expression (1.0) has type float but an expression was expected of 
int

Naively trying to enforce polymorphism doesn't work either:

let print_both: 'a. ('a -> 'a) -> unit = fun f ->
  print_int (f 1);
  print_float (f 1.0)

As a matter of fact, neither will this:

let print1: 'a. ('a -> 'a) -> unit = fun f -> print_int (f 1)

Error: This definition has type (int -> int) -> unit
which is less general than 'a. ('a -> 'a) -> unit

What am I missing? How would you go about writing such a function?

Many thanks,
Guillaume

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

end of thread, other threads:[~2016-05-16 19:10 UTC | newest]

Thread overview: 9+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2016-05-16 15:45 [Caml-list] issue with polymorphism Guillaume Hennequin
2016-05-16 15:57 ` Gabriel Scherer
2016-05-16 16:55   ` Guillaume Hennequin
2016-05-16 17:32     ` Gerd Stolpmann
2016-05-16 18:49       ` Yotam Barnoy
2016-05-16 18:53         ` Gregory Malecha
2016-05-16 19:04           ` Yotam Barnoy
2016-05-16 19:09             ` Gregory Malecha
2016-05-16 15:57 ` Nicolas Ojeda Bar

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