Browse thread
stl?
[
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: | -- (:) |
| From: | Christophe TROESTLER <Christophe.Troestler+ocaml@u...> |
| 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
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