fork download
  1. import Control.Applicative
  2. import Data.Bits
  3. import Data.Char
  4. import Data.List
  5. import Data.Tuple
  6.  
  7. main :: IO ()
  8. main = mapM_ putStrLn $ [f534, f534', g534] <*> [0..10]
  9.  
  10. f534 :: Integral a => a -> String
  11. f534 =
  12. flip (map . (((intToDigit . signum) .) . (.&.) . fromIntegral))
  13. =<< takeWhile (not . (== 0)) . iterate (`div` 2) .
  14. bit . floorLogBase2FromIntegral .
  15. (if' id (const nnErr) =<< (>= 0))
  16.  
  17. f534' :: Integral a => a -> String
  18. f534' =
  19. ((map intToDigitFromIntegral . snd) .) . flip (mapAccumR divMod)
  20. =<< flip replicate 2 . succ . floorLogBase2FromIntegral .
  21. (if' id (const nnErr) =<< (>= 0))
  22.  
  23. g534 :: Integral a => a -> String
  24. g534 = if' (const "0") (map intToDigitFromIntegral . reverse . unfoldr (if' (const Nothing) (Just . swap . (`divMod` 2)) =<< (== 0)) . (if' id (const nnErr) =<< (>= 0))) =<< (== 0)
  25.  
  26. nnErr :: e
  27. nnErr = error "applied to negative number"
  28.  
  29. floorLogBase2FromIntegral :: (Integral a, Integral b) => a -> b
  30. floorLogBase2FromIntegral = floor . logBase 2 . fromIntegral
  31.  
  32. intToDigitFromIntegral :: Integral a => a -> Char
  33. intToDigitFromIntegral = intToDigit . fromIntegral
  34.  
  35. if' :: a -> a -> Bool -> a
  36. if' f g p = if p then f else g
  37.  
Success #stdin #stdout 0s 6256KB
stdin
Standard input is empty
stdout
0
1
10
11
100
101
110
111
1000
1001
1010
0
1
10
11
100
101
110
111
1000
1001
1010
0
1
10
11
100
101
110
111
1000
1001
1010