From: Michael Neumann Date: 2003-11-20T16:59:39+09:00 Subject: Re: Ocaml's typing (was Re: "stereotyping") On Thu, Nov 20, 2003 at 01:12:15PM +0900, Steven@ruby-lang.org wrote: > Austin Ziegler writes: > >Consider generics in Java (templates in C++). These effectively > >introduce the sort of dynamicity that is found in Perl, Python, and > >Ruby. Instead of having to do: > > int max(int x, int y) { return x >= y ? x : y } > > float max(float x, float y) { return x >= y ? x : y } > > double max(double x, double y) { return x >= y ? x : y } > >You can do: > > def max(x, y); x >= y ? x : y; end > >I know which I would prefer, and C++'s move toward generics is a > >halting step toward that step. > > BTW, to see a different point of view, you might investigate > Ocaml (or other ML languages, or Haskell). Ocaml is strongly, > statically type-checked. Here is max: > > let max x y = if x > y then x else y > > (Note that there are no type declarations!) > > # max 3 4;; > - : int = 4 > # max 3.0 4.0;; > - : float = 4 But in Ocaml 3.4 + 1.2 is not allowed, as + is only defined on integers (there's no type overloading). So you have to use +. for floating point addition, *. for multiplication, print_int, print_string, print_float etc. Sometimes, that's pretty ugly , IMHO. > Why does this work? How can max return an int the first time, and > a float the second? Because the type declaration for max (as > inferred by the compiler) is: > > max : 'a -> 'a -> 'a = Indeed, this does only work, as the comparison operators are defined internally for every type. You cannot do this with your own funtioncs, say: if (greater x y) then x else y This is where Haskell & Co is clearly better (or GCaml, generic OCaml). Regards, Michael