Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
27
Task/Binary-digits/Haskell/binary-digits-1.hs
Normal file
27
Task/Binary-digits/Haskell/binary-digits-1.hs
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import Data.List
|
||||
import Numeric
|
||||
import Text.Printf
|
||||
|
||||
-- Use the built-in function showBin.
|
||||
toBin n = showBin n ""
|
||||
|
||||
-- Use the built-in function showIntAtBase.
|
||||
toBin n = showIntAtBase 2 ("01" !!) n ""
|
||||
|
||||
-- Implement our own version.
|
||||
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 . reverse . 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)
|
||||
|
||||
main = do
|
||||
putStrLn $ printf "%4s %14s %14s" "N" "toBin" "toBin1"
|
||||
mapM_ printToBin [5, 50, 9000]
|
||||
23
Task/Binary-digits/Haskell/binary-digits-2.hs
Normal file
23
Task/Binary-digits/Haskell/binary-digits-2.hs
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import Data.Bifunctor (first)
|
||||
import Data.List (unfoldr)
|
||||
import Data.Tuple (swap)
|
||||
|
||||
---------------------- BINARY DIGITS ---------------------
|
||||
|
||||
binaryDigits :: Int -> String
|
||||
binaryDigits = reverse . unfoldr go
|
||||
where
|
||||
go 0 = Nothing
|
||||
go n = Just . first ("01" !!) . swap . quotRem n $ 2
|
||||
|
||||
|
||||
--------------------------- TEST -------------------------
|
||||
main :: IO ()
|
||||
main =
|
||||
mapM_
|
||||
( putStrLn
|
||||
. ( ((<>) . (<> " -> ") . show)
|
||||
<*> binaryDigits
|
||||
)
|
||||
)
|
||||
[5, 50, 9000]
|
||||
Loading…
Add table
Add a link
Reference in a new issue