Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module HW1.T2
- ( N (..)
- , nplus
- , nmult
- , nsub
- , nFromNatural
- , nToNum
- , ncmp
- , nEven
- , nOdd
- , ndiv
- , nmod
- ) where
- import Numeric.Natural
- data N = Z | S N
- nplus :: N -> N -> N
- nplus Z n = n
- nplus (S n) m = S (nplus n m)
- nmult :: N -> N -> N
- nmult Z _ = Z
- nmult (S n) m = nplus m (nmult n m)
- nsub :: N -> N -> Maybe N
- nsub Z Z = Just Z
- nsub Z _ = Nothing
- nsub n Z = Just n
- nsub (S m) (S n) = nsub m n
- ncmp :: N -> N -> Ordering
- ncmp Z Z = EQ
- ncmp _ Z = GT
- ncmp Z _ = LT
- ncmp (S m) (S n) = ncmp m n
- nFromNatural :: Natural -> N
- nFromNatural 0 = Z
- nFromNatural n = S (nFromNatural (n - 1))
- nToNum :: Num a => N -> a
- nToNum Z = 0
- nToNum (S n) = nToNum n + 1
- nEven :: N -> Bool
- nEven Z = True
- nEven (S Z) = False
- nEven (S (S n)) = nEven n
- nOdd :: N -> Bool
- nOdd Z = False
- nOdd (S n) = nEven n
- ndiv :: N -> N -> N
- ndiv _ Z = error "Division by zero"
- ndiv n m
- | ncmp n m == LT = Z
- | otherwise = case nsub n m of
- Just result -> S (ndiv result m)
- Nothing -> Z
- nmod :: N -> N -> N
- nmod _ Z = error "Division by zero"
- nmod n m
- | ncmp n m == LT = n
- | otherwise = case nsub n m of
- Just result -> nmod result m
- Nothing -> Z
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement