-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBigNumber.hs
279 lines (209 loc) · 9.08 KB
/
BigNumber.hs
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
module BigNumber (BigNumber, scanner, output, somaBN, subBN, mulBN, divBN, safeDivBN, isGreaterThan) where
import Data.Char ( intToDigit, digitToInt )
-- TYPE DEFINITION
{-
Absolute value of a number, represented by a list of its decimal digits
-}
type AbsoluteNum = [Int]
{-
Bool -> True if it's a negative number and False otherwise
AbsoluteNum -> Absolute value of the number (list of the number's digits)
-}
type BigNumber = (Bool, AbsoluteNum)
-- INPUT/OUTPUT FUNCTIONS
{-
Converts a string into a BigNumber. A negative number is represented using a '-' at the start of the string
-}
scanner :: String -> BigNumber
scanner numString
| snd num == [0] = (False, [0]) -- A -0 is stored as a regular 0
| otherwise = num
where num = if head numString == '-'
then (True, trimZeros [digitToInt c | c <- tail numString])
else (False, trimZeros [digitToInt c | c <- numString])
{-
Converts a BigNumber into a string. A negative number is represented using a '-' at the start of the string
-}
output :: BigNumber -> String
output bigNum
| isNegative = "-" ++ numString
| otherwise = numString
where isNegative = fst bigNum
numList = snd bigNum
numString = [intToDigit n | n <- numList]
-- AUXILIARY ABSOLUTENUM FUNCTIONS
{-
Removes trailing zeros from the integer list
-}
trimZeros :: AbsoluteNum -> AbsoluteNum
trimZeros xs
| null num = [0]
| otherwise = num
where num = dropWhile (==0) xs
{-
Two AbsoluteNums are normalizing by making their lists the same size and reverting them, to make calculations easier
-}
normalize :: AbsoluteNum -> AbsoluteNum -> (AbsoluteNum, AbsoluteNum)
normalize a b = (normalizedA, normalizedB)
where lenDiff = length a - length b
normalizedA = reverse a ++ replicate (-lenDiff) 0
normalizedB = reverse b ++ replicate lenDiff 0
{-
Extracts the digits of a sum/sub and puts them in the right order again, while removing carries and excessive 0s
-}
getResult :: [(Int, Int)] -> AbsoluteNum
getResult xs
| null num = [0]
| otherwise = num
where num = dropWhile (==0) (reverse [fst tup | tup <- xs])
{-
Compares two AbsoluteNums and returns True if the first one is greater than the second
-}
isGreaterThan :: AbsoluteNum -> AbsoluteNum -> Bool
isGreaterThan a b
| length a /= length b = length a > length b
| null cmp = False -- They're equal
| otherwise = uncurry (>) (head cmp) -- check greatest different digit
where cmp = dropWhile (uncurry (==)) (zip a b)
-- AUXILIARY SUM FUNCTIONS
sumAbsolute :: AbsoluteNum -> AbsoluteNum -> AbsoluteNum
-- The zip combines the modular sum of the digits with the corresponding carry
sumAbsolute a b = getResult (sumCarries (zipWith sumWithCarry normalizedA normalizedB))
where (normalizedA, normalizedB) = normalize a b
sumWithCarry :: Int -> Int -> (Int, Int)
sumWithCarry x y = (total`mod`10, total`div`10)
where total = x + y
{-
Uses the carries calculated previously and adds them in the corresponding digit
-}
sumCarries :: [(Int, Int)] -> [(Int, Int)]
sumCarries xs = foldl sumCarry [] (xs ++ [(0, 0)])
where sumCarry :: [(Int, Int)] -> (Int, Int) -> [(Int, Int)]
sumCarry [] pair = [pair]
sumCarry acc (soma, carry) = init acc ++ [(prevSoma, 0)] ++ [sumWithCarry (soma + carry*10) prevCarry]
where (prevSoma, prevCarry) = last acc
-- AUXILIARY SUB FUNCTIONS
{-
Subtracts a smaller AbsoluteNum (2nd argument) from a greater AbsoluteNum (1st argument)
-}
subAbsolute :: AbsoluteNum -> AbsoluteNum -> AbsoluteNum
subAbsolute a b = getResult (subCarries (zipWith subWithCarry normalizedA normalizedB))
where (normalizedA, normalizedB) = normalize a b
subWithCarry :: Int -> Int -> (Int, Int)
subWithCarry x y
| diff >= 0 = (diff, 0)
| otherwise = (diff + 10, 1)
where diff = x - y
{-
Uses the carries calculated previously and subtracts them in the corresponding digit
-}
subCarries :: [(Int, Int)] -> [(Int, Int)]
subCarries = foldl subCarry []
where subCarry :: [(Int, Int)] -> (Int, Int) -> [(Int, Int)]
subCarry [] pair = [pair]
subCarry acc (sub, carry) = init acc ++ [(prevSub, 0)] ++ [subWithCarry (sub - carry*10) prevCarry]
where (prevSub, prevCarry) = last acc
-- AUXILIARY MUL FUNCTIONS
{-
Multiplies an AbsoluteNum by another one, by multiplying each of the latter's digits and then adding everything accordingly
-}
mulAbsolute :: AbsoluteNum -> AbsoluteNum -> AbsoluteNum
-- The reverse allows us to reuse sumAbsolute
mulAbsolute a b = foldl (\acc num -> sumAbsolute acc (reverse num)) [0] digitMuls
where normalizedA = reverse a
normalizedB = reverse b
digitMuls = mulAllDigits normalizedA normalizedB
mulWithCarry :: Int -> Int -> (Int, Int)
mulWithCarry x y = (total`mod`10, total`div`10)
where total = x * y
{-
Multiplies an AbsoluteNum by a given digit
-}
mulByDigit :: AbsoluteNum -> Int -> AbsoluteNum
-- Reverse it again to continue making calculations afterwards
mulByDigit num dig = reverse (getResult (sumCarries (map (`mulWithCarry` dig) num)))
{-
Multiplies the first number by all the digits in the second one and returns the results in a list of AbsoluteNums
-}
mulAllDigits :: AbsoluteNum -> AbsoluteNum -> [AbsoluteNum]
-- The 0's at the start account for the position of the digit being multiplied
mulAllDigits a b = [replicate i 0 ++ (rawMultiplications !! i) | i <- [0..end]]
where rawMultiplications = map (\x -> a `mulByDigit` x) b
end = length rawMultiplications - 1
-- AUXILIARY DIV FUNCTIONS
{-
Divides two AbsoluteNums by recursively subtracting the denominator from the numerator and counting the quotient,
until the denominator is greater than the numerator
-}
divWithSubtraction :: AbsoluteNum -> AbsoluteNum -> (AbsoluteNum, AbsoluteNum)
divWithSubtraction num denom
| isDenomGreater = ([0], num)
| otherwise = (sumAbsolute [1] nextQ, nextR)
where isDenomGreater = isGreaterThan denom num
(nextQ, nextR) = divWithSubtraction (subAbsolute num denom) denom
{-
Splits the numerator until the first part is greater than the denominator
-}
splitNumerator :: AbsoluteNum -> AbsoluteNum -> AbsoluteNum -> (AbsoluteNum, AbsoluteNum)
splitNumerator denom divPart rest
| not isDenomGreater = (divPart, rest)
| otherwise = splitNumerator denom (divPart ++ [head rest]) (tail rest)
where isDenomGreater = isGreaterThan denom divPart
{-
Takes the split numerator and starts calculating the result by dividing num1 by denom, keeping the rest
and recursively adding one digit to num1 and to the quotient
-}
divAux :: AbsoluteNum -> AbsoluteNum -> AbsoluteNum -> AbsoluteNum -> (AbsoluteNum, AbsoluteNum)
divAux num1 num2 denom quotient
| null num2 = (quotient ++ newQuot, newRest) -- last call. Here, we want to keep a [0] rest
| otherwise = divAux (rest ++ [head num2]) (tail num2) denom (quotient ++ newQuot)
where (newQuot, newRest) = divWithSubtraction num1 denom
rest = dropWhile (== 0) newRest -- drop all of trailing zeros
{-
Divides two AbsoluteNum's, by calling divAux after dividing the numerator accordingly
-}
divAbsolute :: AbsoluteNum -> AbsoluteNum -> (AbsoluteNum, AbsoluteNum)
divAbsolute num denom
| isDenomGreater = ([0], num)
| otherwise = divAux divPart finalPart denom [] -- Start the recursive function
where isDenomGreater = isGreaterThan denom num
(divPart, finalPart) = splitNumerator denom [] num
-- MAIN ARITHMETIC FUNCTIONS
somaBN :: BigNumber -> BigNumber -> BigNumber
somaBN a b
| isANeg == isBNeg = (isANeg, sumAbsolute absoluteA absoluteB)
| isAGreater = (isANeg, subAbsolute absoluteA absoluteB)
| isBGreater = (isBNeg, subAbsolute absoluteB absoluteA)
| otherwise = (False, [0]) -- Simetric
where isANeg = fst a
isBNeg = fst b
absoluteA = snd a
absoluteB = snd b
isAGreater = isGreaterThan absoluteA absoluteB
isBGreater = isGreaterThan absoluteB absoluteA
subBN :: BigNumber -> BigNumber -> BigNumber
subBN a b
| isANeg /= isBNeg = (isANeg, sumAbsolute absoluteA absoluteB)
| isAGreater = (isANeg, subAbsolute absoluteA absoluteB)
| isBGreater = (isBNeg, subAbsolute absoluteB absoluteA)
| otherwise = (False, [0]) -- Equal
where isANeg = fst a
isBNeg = fst b
absoluteA = snd a
absoluteB = snd b
isAGreater = isGreaterThan absoluteA absoluteB
isBGreater = isGreaterThan absoluteB absoluteA
mulBN :: BigNumber -> BigNumber -> BigNumber
mulBN a b
| isANeg == isBNeg = (False, result)
| otherwise = (True, result)
where isANeg = fst a
isBNeg = fst b
result = mulAbsolute (snd a) (snd b)
divBN :: BigNumber -> BigNumber -> (BigNumber, BigNumber)
divBN a b = ((False, resultQ), (False, resultR))
where (resultQ, resultR) = divAbsolute (snd a) (snd b)
safeDivBN :: BigNumber -> BigNumber -> Maybe (BigNumber, BigNumber)
safeDivBN a b
| b == scanner "0" = Nothing
| otherwise = Just (divBN a b)