Le Thursday 05 Jan 2012 à 13:35:37 (-0800), DelPhiNus a écrit :
> Actually last time I wrote pseudo-code without checking if it was
> correct...
> Yes the two other functions should be nested.
>
> I don't know if something was wrong in my real code but somehow, the
> type of f x was inferred for the first use of this function, then I
> got an error later mentioning a type incompatibility showing the
> expected type that was inferred earlier.
I think you should post a clear example so that I do not get confused
and do not get things wrong.
> Regarding this:
> > Actually I am not very keen in writing a top-level function with all
> > necessary arguments each time I need to do some generic processing
> > that is specific to one master function.
>
> I just mean that the language sucks if it provides the polymorphic
> capability only at the top level.
No, the language provides a whole lot of possibilities both for
polymorphism and for recursion. You just have to pick the right one at
the right time.
The "let ... in" construct allows you to use polymorphism inside nested
code. Typically, the fact that
let _ = let f x = x in (f 1), (f [])
typechecks properlies means that even though f is 'a -> 'a, the 'a type
gets instantiated separately each time in 'f 1' and 'f []'. So you do
have polymorphism.
However,
let rec f x =
let _ = f 1 in
let _ = f [] in
()
will not typecheck, because inside the declaration body, f is assumed to
be 'a -> _ , and 'a gets unified with int and also with _ list. So this
doesn't typecheck.
However, you have polymorphic recursion since recent versions of OCaml.
type 'a t = A of 'a list t
let rec f : 'a. 'a t -> _ = fun (A x) -> f x
does compile. As f's type is explicitely quantified, OCaml knows how to
typecheck properly the nested f as _ list t -> _.
If you forget the 'a. prefix, it does not typecheck anymore:
let rec f : 'a t -> _ = fun (A x) -> f x
fails to typecheck miserably with the following error:
Error: This expression has type 'a t -> 'b
but an expression was expected of type 'a list t -> 'b
There's lots of way to make polymorphism and recursion nicely cohabit,
but they are not always the most obvious or syntactically light.
> I will try your code tomorrow... and check if there was something
> wrong in my code.
>
> Thanks
--
Guillaume Yziquel
http://yziquel.homelinux.org
--
You received this message because you are subscribed to the Google Groups
"ocaml-developer" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/ocaml-developer?hl=en
For other OCaml forums, see http://caml.inria.fr/resources/forums.en.html