Advertisement
alyoshinkkaa

Untitled

Sep 23rd, 2024
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. module HW1.T2
  2.   ( N (..)
  3.   , nplus
  4.   , nmult
  5.   , nsub
  6.   , nFromNatural
  7.   , nToNum
  8.   , ncmp
  9.   , nEven
  10.   , nOdd
  11.   , ndiv
  12.   , nmod
  13.   ) where
  14.  
  15. import Numeric.Natural
  16.  
  17. data N = Z | S N
  18.  
  19. nplus :: N -> N -> N
  20. nplus Z n = n
  21. nplus (S n) m = S (nplus n m)
  22.  
  23. nmult :: N -> N -> N
  24. nmult Z _ = Z
  25. nmult (S n) m = nplus m (nmult n m)
  26.  
  27. nsub :: N -> N -> Maybe N
  28. nsub Z Z = Just Z
  29. nsub Z _ = Nothing
  30. nsub n Z = Just n
  31. nsub (S m) (S n) = nsub m n
  32.  
  33. ncmp :: N -> N -> Ordering
  34. ncmp Z Z = EQ
  35. ncmp _ Z = GT
  36. ncmp Z _ = LT
  37. ncmp (S m) (S n) = ncmp m n
  38.  
  39. nFromNatural :: Natural -> N
  40. nFromNatural 0 = Z
  41. nFromNatural n = S (nFromNatural (n - 1))
  42.  
  43. nToNum :: Num a => N -> a
  44. nToNum Z = 0
  45. nToNum (S n) = nToNum n + 1
  46.  
  47. nEven :: N -> Bool
  48. nEven Z = True
  49. nEven (S Z) = False
  50. nEven (S (S n)) = nEven n
  51.  
  52. nOdd :: N -> Bool
  53. nOdd Z = False
  54. nOdd (S n) = nEven n
  55.  
  56. ndiv :: N -> N -> N
  57. ndiv _ Z = error "Division by zero"
  58. ndiv n m
  59.     | ncmp n m == LT = Z
  60.     | otherwise = case nsub n m of
  61.         Just result -> S (ndiv result m)
  62.         Nothing -> Z
  63.  
  64. nmod :: N -> N -> N
  65. nmod _ Z = error "Division by zero"
  66. nmod n m
  67.     | ncmp n m == LT = n
  68.     | otherwise = case nsub n m of
  69.         Just result -> nmod result m
  70.         Nothing -> Z
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement