This site is updated infrequently. For up-to-date information, please visit the new OCaml website at ocaml.org.

stl?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
 Date: 2009-03-04 (14:08) From: Christophe TROESTLER Subject: Re: [Caml-list] stl?
```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
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