-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBinarySearch.dats
73 lines (64 loc) · 1.04 KB
/
BinarySearch.dats
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
(* ****** ****** *)
#include "share/atspre_staload.hats"
#include "share/atspre_staload_libats_ML.hats"
(* ****** ****** *)
typedef
freal = cfun(double, double)
typedef
interval = $tup(double, double)
(* ****** ****** *)
fun
interval
(
a: double, b: double
) : interval =
(
if a <= b then $tup(a, b) else $tup(b, a)
)
(* ****** ****** *)
//
fun
BinarySearch
(
f : freal
,
a : double, b : double
) : stream(interval) = $delay
let
//
val m = (a+b) / 2
//
in
if f(m) >= 0
then stream_cons(interval(a, b), BinarySearch(f, a, m))
else stream_cons(interval(a, b), BinarySearch(f, m, b))
// end of [if]
end // end of [BinarySearch]
//
(* ****** ****** *)
implement
main0() = let
//
val f =
lam
(
x: double
): double =<cloref1>
(x * x * x - x - 2.0)
//
#define EPSILON 1E-6
//
val
intervals =
BinarySearch(f, 1.0, 2.0)
val
intervals =
(intervals).filter()(lam($tup(a, b)) => (b-a) < EPSILON)
//
val $tup(a, b) = intervals[0]
//
in
println! ("intervals[0] = ", (a+b)/2)
end // end of [main0]
(* ****** ****** *)
(* end of [BinarySearch.dats] *)