Advertisement
Guest User

RatOps

a guest
Dec 6th, 2019
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. module RatOps where
  2. type Rat = (Int,Int)
  3.  
  4. asop :: Num z => (z -> z -> z) -> (z,z) -> (z,z) -> (z,z)
  5. asop op (z1,n1)(z2,n2) = ((z1*n2) `op` (z2*n1), (n1*n2))
  6.  
  7. short :: Num z => (z -> z) -> (z,z) -> (z,z)
  8. short (z1,n1) = ((z1/gcd z1 n1), (gcd z1 n1)
  9.  
  10. negn :: Rat -> Bool
  11. negn (z1,n1) = if n1 = 0
  12. then True
  13. else False
  14.  
  15. negz :: Rat -> Bool
  16. negz (z1,n1) = if z1 = 0
  17. then True
  18. else False
  19.  
  20. switch :: Rat -> Rat
  21. switch (z,n) = (n,z)
  22.  
  23. addR :: Rat -> Rat -> Rat
  24. addR x y|negz x = True || (snd y == 1) = (0, 1)
  25. |negn y = True || (fst x == 0) = (0, 0)
  26. |otherwise = short $ asop(+) x y
  27.  
  28. subR :: Rat -> Rat -> Rat
  29. subR x y|negz x = True || (snd y == 1) = (0, 1)
  30. |negn y = True || (fst x == 0) = (0, 0)
  31. |otherwise = short $ asop(-) x y
  32.  
  33. mulR :: Rat -> Rat -> Rat
  34. mulR x y|negz x = True || (snd y == 1) = (0, 1)
  35. |negn y = True || (fst x == 0) = (0, 0)
  36. |otherwise = short ((fst x * fst y),(snd x * snd y)
  37.  
  38. divR :: Rat -> Rat -> Rat
  39. divR x y|negz x = True || (snd y == 1) = (0, 1)
  40. |negn y = True || (fst x == 0) = (0, 0)
  41. |otherwise = short $ x `mulR` (switch y)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement