This site is updated infrequently. For up-to-date information, please visit the new OCaml website at ocaml.org.

[Caml-list] Type inference problem
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
 Date: 2001-06-29 (02:41) From: Jacques Garrigue Subject: Re: [Caml-list] Type inference problem
```> Can anyone explain why O'Caml specializes the following:
>
> let simple ?fn list =
>   let fn = match fn with
>   | Some fn -> fn
>   | None -> fun t -> t in
>   let rec print = function
>     | [] -> ()
>     | x :: xs -> print_endline (fn x); print xs
>   in
>   print list
> val simple : ?fn:(string -> string) -> string list -> unit

The simple answer is type inference:
* fn and (fun t -> t) should have the same type 'a -> 'a
* the result of (fn x) is of type string
* consequently, 'a = string
* and the type of fn is string -> string

Now, what you would want is to distinguish when there is a function
passed and when there is none at the type level.
You cannot do it with optional arguments, but you can use the
following encoding:

module Default : sig
type ('a, 'b) t
val none : ('a, 'a) t
val some : 'a -> ('a, 'b) t
val get : 'a -> ('b, 'a) t -> 'b
val get_lazy : 'a Lazy.t -> ('b, 'a) t -> 'b
end = struct
type ('a,'b) t = Dnone | Dsome of 'a
let none = Dnone
let some x = Dsome x
let get d = function Dnone -> Obj.magic d | Dsome x -> x
let get_lazy d = function Dnone -> Obj.magic (Lazy.force d) | Dsome x -> x
end

let out ~fn x = let fn = Default.get (fun x -> x) fn in print_endline (fn x)
val out : fn:('a -> string, 'b -> 'b) Default.t -> 'a -> unit = <fun>

out ~fn:Default.none "Hello";;
out ~fn:(Default.some string_of_int) 3;;

Would it be possible to include it with optional arguments?
Theoretically, yes, but it would require a new syntax, make typing
more complex, and checking weaker (the type of the default is only
checked the first time the function is called with no argument).
I'm not sure it's worth it.

Jacques Garrigue
-------------------
Bug reports: http://caml.inria.fr/bin/caml-bugs  FAQ: http://caml.inria.fr/FAQ/
To unsubscribe, mail caml-list-request@inria.fr  Archives: http://caml.inria.fr

```