Browse thread
[Caml-list] C++ STL and template features compared with OCaml parametric polymorphism and OO features
[
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: | 2004-09-30 (23:18) |
From: | Jacques Garrigue <garrigue@k...> |
Subject: | Re: [Caml-list] Factoring HOFs |
From: Keith Wansbrough <Keith.Wansbrough@cl.cam.ac.uk> > > Yipes! Ok, so I'm missing some typing subtlety. Why does this end up with a > > single polymorphic type: > > > > # let map_2 m g f x = m g (m f x);; > > val map_2 : ('a -> 'b -> 'b) -> 'a -> 'a -> 'b -> 'b = <fun> > > You want it to have type > > (forall 'a 'b 'f. ('a -> 'b) -> ('a 'f -> 'b 'f)) > -> ('b -> 'c) > -> ('a -> 'b) > -> 'a 'f > -> 'b 'f > > but OCaml doesn't allow nested quantifiers (i.e., higher-rank > polymorphism). > > It actually wouldn't be very hard to support, if you're prepared to > accept the need for the occasional type annotation - see > http://research.microsoft.com/~simonpj/papers/putting/index.htm. OCaml has been supporting nested quantifiers for years. However, they are a little more verbose because we chose to allow unpredicate 2nd order types, which are harder to infer. Look in the manual for polymorphic record fields and polymorphic methods. The former are lighter syntactically, but require an explicit record definition in advance, while the latter allow defining polymorphic values on the fly. But your example also uses constructor variables, which are not available in ocaml. Note however that you can still encode it using a functor: module Map2(M : sig type 'a f val map : ('a -> 'b) -> 'a f -> 'b f end) = struct let map2 g f x = M.map g (M.map f x) end Not much longer, he? You can apply this functor locally with "let module". let to_string l = let module M = Map2(struct type 'a f = 'a list let map = List.map end) in M.map2 string_of_int (fun x -> x + 1) l Jacques ------------------- 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