Skip to content

Instantly share code, notes, and snippets.

@mitsuji
Last active May 24, 2019 12:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mitsuji/31118120c23b3775df4a2b36c6f48eda to your computer and use it in GitHub Desktop.
Save mitsuji/31118120c23b3775df4a2b36c6f48eda 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
step3 :: BWord -> [BWord]
step3 0 = []
step3 n = n : step3 (n - 3)
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
test13 = step3 125
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment