Browse thread
Type error
-
Denis Bueno
- Jonathan Roewen
- Jonathan Roewen
- skaller
- Etienne Miret
- Jacques Garrigue
[
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: | Etienne Miret <etienne.miret@e...> |
| Subject: | Re: [Caml-list] Type error |
On oct 15 2006 at 05:29, Denis Bueno wrote:
> ,----
> | val of_array: ?getter : ('b -> 'a) -> 'b array -> 'a t
> | (** [of_array xs] returns a set containing the elements in
> [xs]. *)
> `----
>
> I get a type error when trying to compile this. I don't know how to
> fix it, or even if it's possible without wrecking my nice of_array
> signature.
Your very nice of_array signature... I'm afraid you're signature is
awful. Basically you're trying to get a 'a -> 'b type, which is
impossible without using Obj.magic, and awful anyway. See, if you do
# let my_array = [| (1,'a') ; (2,'b') |];;
val my_array : (int * char) array = [|(1, 'a'); (2, 'b')|]
# let set = of_array ~getter:snd my_array;;
val set : char list = ['a'; 'b']
This is okay, but if you decide not to give the optional argument:
# let set2 = of_array my_array
Then what type should be inferred for set2? of course the real type
is (int * char) t, but with the signature you gave for of_array you
cannot infer it, since they're is no way to know that the default
value for the optional argument has the type 'a -> 'a.
By implementing of_array with Obj.magic, you get:
# let set2 = of_array my_array;;
val set2 : 'a list = [<poly>; <poly>]
and then you can do funny (and ugly) things:
# add 4 set2;;
- : int list = [4; 354636; 354630]
# add 'c' set2;;
- : char list = ['c'; '\
36'; '\
30']
# add (3,'c') set2;;
- : (int * char) list = [(1, 'a'); (2, 'b'); (3, 'c')]
I implemented of_array this way:
# let of_array ?(getter = fun x -> Obj.magic x) xs =
Array.fold_right (fun x set -> add (getter x) set) xs empty;;
val of_array : ?getter:('a -> 'b) -> 'a array -> 'b list = <fun>
Regards,
Etienne