Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] Type inference + optional parameters
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jacques Garrigue <garrigue@k...>
Subject: Re: [Caml-list] Type inference + optional parameters
From: Christoph Bauer <c_bauer@informatik.uni-kl.de>

> ocamls type inference uses information of optionl arguments. This
> results in a strange behaviour.

Brian Rogoff already answered this one. Do you seriously expect a
type-safe compiler to simply ignore the type of the default value :-)

> Here is an example:
> 
>         Objective Caml version 3.07+beta 2
> 
> # let do_with_opt_conv ?(conv = fun s -> s) a = conv a;;
> do_with_opt_conv ~conv:string_of_int "1";;- : int = 1
> # val do_with_opt_conv : ?conv:('a -> 'a) -> 'a -> 'a = <fun>
> # do_with_opt_conv ~conv:string_of_int "1";;
> 
> Is there a solution? It is not possible to 
> add the "right" type information:
> 
> # let do_with_opt_conv ?(conv : 'a -> 'b = fun s -> s) (a:'a) : 'b = conv a;;
> val do_with_opt_conv : ?conv:('a -> 'a) -> 'a -> 'a = <fun>

The answer is that the function you want cannot be defined with
optional arguments.

Actually, we need a slightly more expressive type to allow this.

module Default : sig
  type ('a,'b) t
  val default : ('a,'a) t
  val custom : 'a -> ('a,'b) t
  val get : (unit -> 'b) -> ('a,'b) t -> 'a
end = struct
  type ('a,'b) t = Custom of 'a | Default
  let default = Default
  let custom x = Custom x
  let get def = function
      Default -> Obj.magic (def ())
    | Custom x -> x
end

Note that you need to use Obj.magic to define the above module, but
the type of [default] ensures that this is sound.

Then you can define your function:

# let do_with_opt_conv ~conv a =
  let conv = Default.get (fun () x -> x) conv in
  conv a ;;
val do_with_opt_conv : conv:('a -> 'b, 'c -> 'c) Default.t -> 'a -> 'b
# do_with_opt_conv ~conv:Default.default 1;;
- : int = 1
# do_with_opt_conv ~conv:(Default.custom string_of_int) 1;;
- : string = "1"

Jacques Garrigue

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