Created
May 24, 2019 10:05
-
-
Save mitsuji/3e9fa5b4c91ec090145a9760616910e7 to your computer and use it in GitHub Desktop.
Word type supports Underflow/Overflow error
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Data.BWord(BWord(..),fromBWord) where | |
newtype BWord = BWord Integer | |
deriving (Eq,Ord,Show) | |
fromBWord :: BWord -> Integer | |
fromBWord (BWord x) = x | |
minBound' :: Integer | |
minBound' = fromIntegral (minBound::Word) | |
maxBound' :: Integer | |
maxBound' = fromIntegral (maxBound::Word) | |
instance Bounded BWord where | |
minBound = fromInteger minBound' | |
maxBound = fromInteger maxBound' | |
mkBWord :: Integer -> BWord | |
mkBWord n | |
| n < minBound' = error "Underflow" | |
| maxBound' < n = error "Overflow" | |
| otherwise = BWord n | |
instance Num BWord where | |
BWord x + BWord y = mkBWord $ x + y | |
BWord x * BWord y = mkBWord $ x * y | |
BWord x - BWord y = mkBWord $ x - y | |
abs x = x | |
signum (BWord 0) = 0 | |
signum (BWord _) = 1 | |
fromInteger = mkBWord | |
test1 = (maxBound::BWord) | |
test2 = (maxBound::BWord) +1 | |
test3 = (maxBound::BWord) -1 +1 | |
test4 = (maxBound::BWord) +1 -1 | |
test5 = (maxBound::BWord) -2 +1 | |
test6 = (maxBound::BWord) +1 -2 | |
test7 = (minBound::BWord) | |
test8 = (minBound::BWord) -1 | |
test9 = (minBound::BWord) +1 -1 | |
test10 = (minBound::BWord) -1 +1 | |
test11 = (minBound::BWord) +2 -1 | |
test12 = (minBound::BWord) -1 +2 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment