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
Why type inference fails in this code
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2009-10-09 (07:09)
From: Gabriel Kerneis <kerneis@p...>
Subject: Re: [Caml-list] Why type inference fails in this code
On Fri, Oct 09, 2009 at 07:25:41AM +0200, wrote:
> ======================================================
> type t = MyInt of int | MyFloat of float | MyString of string ;;
> let foo printerf = function
>   | MyInt i -> printerf string_of_int i
>   | MyFloat x -> printerf string_of_float x
>   | MyString s -> printerf (fun x -> x) s
> ;;
> ======================================================

Type-inference has nothing to do with it, it's the type system itself
which fails.

What is the type you would expect? I guess:
(forall 'a. ('a -> string) -> 'a -> 'b) -> t -> 'b

This is impossible with Ocaml: you cannot have a universal quantifier,
type variables are existantially quantified.

> I read that there are lots of workarounds for the above code snippet,
> but I would like to Know why this code fails and what is the best
> workaround for this type of code.

You have many ways to emulate universal types in Ocaml (objects,
records) and browsing the archives of this list should provide many good

In you very specific case, though, I guess refactoring it is possible:
let foo printerf = function
  | MyInt i -> printerf (string_of_int i)
  | MyFloat x -> printerf (string_of_float x)
  | MyString s -> printerf s

(depending on what your printerf function does, but I can't find any

Gabriel Kerneis