Skip to content

Instantly share code, notes, and snippets.

@mitsuji
Created May 24, 2019 10:05
Show Gist options
  • Save mitsuji/3e9fa5b4c91ec090145a9760616910e7 to your computer and use it in GitHub Desktop.
Save mitsuji/3e9fa5b4c91ec090145a9760616910e7 to your computer and use it in GitHub Desktop.
Word type supports Underflow/Overflow error
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