Jump to content

Binary digits: Difference between revisions

→‎{{header|Haskell}}: Added unfolding implementation
(→‎{{header|Haskell}}: Added unfolding implementation)
Line 1,190:
toBin1 0 = []
toBin1 x = (toBin1 $ x `div` 2) ++ (show $ x `mod` 2)
 
-- Or even more efficient (due to fusion) and universal implementation
toBin2 = foldMap show . toBase 2
 
toBase base = unfoldr modDiv
where modDiv 0 = Nothing
modDiv n = let (q, r) = (n `divMod` base) in Just (r, q)
 
 
printToBin n = putStrLn $ printf "%4d %14s %14s" n (toBin n) (toBin1 n)
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.