On Wed, 4 Mar 2009 01:11:18 -0500, Brian Hurt wrote:
> 
> Try this.  Let's reimplement Haskell's Fractional class, in Ocaml, and
> then do Newton's method using this new Fractional class.  [...]
> 
> module type Fractional = sig
>       type t
>       val ( +. ) : t -> t -> t
>       val ( -. ) : t -> t -> t
>       val ( *. ) : t -> t -> t
>       val ( /. ) : t -> t -> t
>       val fabs : t -> t
>       (* other functions elided from brevity *)
> end;;

Small point: you forgot the comparison functions — they are necessary
for Ratio.

> [...]  once you realize that the definitions of Fractional,
> FloatFractional, and RatioFractional all should be in the standard
> library (and the latter two should be just called Float and Ratio).

Well, they sort of are in the standard library already thanks to
Delimited Overloading!  http://pa-do.forge.ocamlcore.org/
With it, your code can simply be written as a macro:

  DEFINE NEWTON(M) = M.(
    let rec newton epsilon f df x =
      let x' = x - f x / df x in
      if abs(x - x') < epsilon then x'
      else newton epsilon f df x' in
    newton)
  
  let float_newton = NEWTON(Float)
  
  let ratio_newton = NEWTON(Ratio)
  
(and with no performance lost at all for those concerned with clock
cycles).

I have released a new version of Delimited Overloading with that new
example (ad-hoc-newton.ml).

Enjoy,
ChriS

_______________________________________________
Caml-list mailing list. Subscription management:
http://yquem.inria.fr/cgi-bin/mailman/listinfo/caml-list
Archives: http://caml.inria.fr
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners
Bug reports: http://caml.inria.fr/bin/caml-bugs

Reply via email to