Last active
September 9, 2022 17:45
-
-
Save kbridge/98c38e2f1f1b6830ace515681803b6fa to your computer and use it in GitHub Desktop.
A complex implementation of integer to binary conversion in Haskell
This file contains hidden or 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
| import Data.Bits (Bits (testBit), FiniteBits(countLeadingZeros, finiteBitSize)) | |
| import Data.Char (intToDigit) | |
| toBinary :: FiniteBits a => a -> [Char] | |
| toBinary n = [charOfBitAt i n | i <- reverse [0..(bitLength n - 1)]] | |
| where | |
| bitLength = (-) <$> finiteBitSize <*> countLeadingZeros | |
| charOfBitAt i = intToDigit . fromEnum . flip testBit i |
This file contains hidden or 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
| import Control.Monad (forM_) | |
| import Text.Printf (printf) | |
| example :: IO () | |
| example = forM_ [(0 :: Int)..20] $ \n -> printf "%2d -> %s\n" n (show $ toBinary n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment