Skip to content

Commit fc0866a

Browse files
committed
Solve 'Convert to Binary' kata
1 parent c09ffd3 commit fc0866a

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/Binary.hs

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
module Binary (toBinary) where
2+
3+
-- https://www.codewars.com/kata/59fca81a5712f9fa4700159a/train/haskell
4+
5+
toBinary :: Integer -> Integer
6+
toBinary = bitsToBinary . integerToBits
7+
8+
integerToBits :: Integer -> [Bool]
9+
integerToBits 0 = []
10+
integerToBits x
11+
| even x = False : integerToBits (x `div` 2)
12+
| otherwise = True : integerToBits (x `div` 2)
13+
14+
bitsToBinary :: [Bool] -> Integer
15+
bitsToBinary [] = 0
16+
bitsToBinary (False : xs) = (* 10) . bitsToBinary $ xs
17+
bitsToBinary (True : xs) = (+ 1) . (* 10) . bitsToBinary $ xs
18+
19+
-- #againwhatlearned: Use `showBin` of the `Numeric` module
20+
-- import Numeric (showBin)
21+
-- toBinary :: Integer -> Integer
22+
-- toBinary = read . flip showBin ""

test/BinarySpec.hs

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
module BinarySpec where
2+
3+
import Binary (toBinary)
4+
import Test.Hspec
5+
6+
spec :: Spec
7+
spec = do
8+
describe "Fixed Tests" $ do
9+
it "toBinary 1" $ toBinary 1 `shouldBe` 1
10+
it "toBinary 2" $ toBinary 2 `shouldBe` 10
11+
it "toBinary 3" $ toBinary 3 `shouldBe` 11
12+
it "toBinary 5" $ toBinary 5 `shouldBe` 101

0 commit comments

Comments
 (0)