-
Notifications
You must be signed in to change notification settings - Fork 0
/
6th_Sept_data_structure_1
84 lines (49 loc) · 1.33 KB
/
6th_Sept_data_structure_1
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
74
75
76
77
// simplest data structure : pair
// (x,y)
function make_point(x,y){
return component => component === 0 ? x : y;
}
// to get x
function x_of(p){
return p(0);
}
function y_of(p){
return p(1);
}
x_of(make_point(3,4));
const pair = (x,y) => f => f(x,y);
// const p = pair(1,2);
// input to function f needs two arguments
// f => (x,y) => x
// (f => f(1,2)(lambda expression input for f))
const head = p => p((x,y) => x);
const tail = p => p((x,y) => y);
// rational number
// a pair consisting of a denominator and numerator
function make_rat(n, d){
return pair(n, d);
}
function numer(x){
return head(x);
}
function denom(x){
return tail(x);
}
// rational number arithmetic system
function add_rat(x, y){
return make_rat(numer(x) * denom(y) +
numer(y) * denom(y),
denom(x) * denom(y));
}
// similarly for subtraction, multiplication and division
// equality of rational numbers
// dont have to reduce to lowest form to check
// instead can cross multiply and check
// visualising rational numbers
function rat_to_string(x) {
return stringify(numer(x)) + '/' + stringify(denom(x));
}
display(rat_to_string(add_rat(make_rat(1,2), make_rat(1,3))));
// why is the above giving wrong answer?
// gcd
// implementation details of this invisible to user