Skip to content

Instantly share code, notes, and snippets.

@kbridge
Last active September 9, 2022 17:45
Show Gist options
  • Select an option

  • Save kbridge/98c38e2f1f1b6830ace515681803b6fa to your computer and use it in GitHub Desktop.

Select an option

Save kbridge/98c38e2f1f1b6830ace515681803b6fa to your computer and use it in GitHub Desktop.
A complex implementation of integer to binary conversion in Haskell
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
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