Skip to content

Instantly share code, notes, and snippets.

@brandonchinn178
Last active February 27, 2021 18:00
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 brandonchinn178/ab2701f6bbfe3c68ed520d2df5345fcd to your computer and use it in GitHub Desktop.
Save brandonchinn178/ab2701f6bbfe3c68ed520d2df5345fcd to your computer and use it in GitHub Desktop.
data Digit = Zero | One | Two | Three | Four | Five | Six | Seven | Eight | Nine
deriving (Enum)
zero, one, ten :: Int
zero = fromEnum Zero
one = fromEnum One
ten = succ $ fromEnum Nine
main :: IO ()
main = mapM_ print [one .. ten * ten]
import Data.List (elemIndex)
import Data.Maybe (fromJust)
data Digit = Zero | One | Two | Three | Four | Five | Six | Seven | Eight | Nine
deriving (Eq, Enum, Bounded)
instance Show Digit where
show = show . fromEnum
newtype Number = Number' { digits :: [Digit] }
mkNumber :: [Digit] -> Number
mkNumber = Number' . dropWhile (== Zero)
instance Show Number where
show = concatMap show . digits
oneToHundred :: [Number]
oneToHundred = tail zeroToNinetyNine ++ [oneHundred]
where
zeroToNinetyNine =
[ mkNumber [tensDigit, onesDigit]
| tensDigit <- [minBound..maxBound]
, onesDigit <- [minBound..maxBound]
]
oneHundred = mkNumber [One, Zero, Zero]
main :: IO ()
main = mapM_ print oneToHundred
data Digit = Zero | One | Two | Three | Four | Five | Six | Seven | Eight | Nine
deriving (Eq, Enum, Bounded)
instance Show Digit where
show = show . fromEnum
newtype Number = Number { digits :: [Digit] }
deriving (Eq)
instance Show Number where
show = concatMap show . digits
incr :: Number -> Number
incr = Number . incrFinal . reverse . digits
where
incrFinal [] = error $ "Called incr on Number with no digits"
incrFinal (d:ds) =
let (carry, d') = incrDigit d
in propagateCarry carry ds ++ [d']
propagateCarry carry [] = if carry then [One] else []
propagateCarry carry (d:ds) =
let (carry', d') = if carry then incrDigit d else (False, d)
in propagateCarry carry' ds ++ [d']
incrDigit Nine = (True, Zero)
incrDigit d = (False, succ d)
main :: IO ()
main = mapM_ print $ range one oneHundred
where
one = Number [One]
oneHundred = Number [One, Zero, Zero]
range start end = takeWhile (/= incr end) $ iterate incr start
@mihaimaruseac
Copy link

oneToHundred = map mkNumber [[Zero, Zero, One] ... [One, Zero, Zero]]

Untested, but shorter :) Might need to make it a triple instead of list and a function to convert from tuple to list but would still be shorter :)

@brandonchinn178
Copy link
Author

@mihaimaruseac No, there's no Enum instance for tuples 😢 but if arithmetic operations are ok, I have a better solution

@mihaimaruseac
Copy link

Oh, right. The arithmetic solution is great.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment