RosettaCodeData/Task/Continued-fraction/ATS/continued-fraction.ats
2023-07-01 13:44:08 -04:00

70 lines
1.2 KiB
Text

#include
"share/atspre_staload.hats"
//
(* ****** ****** *)
//
(*
** a coefficient function creates double values from in paramters
*)
typedef coeff_f = int -> double
//
(*
** a continued fraction is described by a record of two coefficent
** functions a and b
*)
typedef frac = @{a= coeff_f, b= coeff_f}
//
(* ****** ****** *)
fun calc
(
f: frac, n: int
) : double = let
//
(*
** recursive definition of the approximation
*)
fun loop
(
n: int, r: double
) : double =
(
if n = 0
then f.a(0) + r
else loop (n - 1, f.b(n) / (f.a(n) + r))
// end of [if]
)
//
in
loop (n, 0.0)
end // end of [calc]
(* ****** ****** *)
val sqrt2 = @{
a= lam (n: int): double => if n = 0 then 1.0 else 2.0
,
b= lam (n: int): double => 1.0
} (* end of [val] *)
val napier = @{
a= lam (n: int): double => if n = 0 then 2.0 else 1.0 * n
,
b= lam (n: int): double => if n = 1 then 1.0 else n - 1.0
} (* end of [val] *)
val pi = @{
a= lam (n: int): double => if n = 0 then 3.0 else 6.0
,
b= lam (n: int): double => let val x = 2.0 * n - 1 in x * x end
}
(* ****** ****** *)
implement
main0 () =
(
println! ("sqrt2 = ", calc(sqrt2, 100));
println! ("napier = ", calc(napier, 100));
println! (" pi = ", calc( pi , 100));
) (* end of [main0] *)