Skip to content

Instantly share code, notes, and snippets.

@adomokos
Created April 26, 2017 04:42
Show Gist options
  • Save adomokos/b7439ff467fdf08fc180641833c420be to your computer and use it in GitHub Desktop.
Save adomokos/b7439ff467fdf08fc180641833c420be to your computer and use it in GitHub Desktop.
The Roman Numerals kata in Haskell
import Test.Hspec
import Test.QuickCheck
import Control.Exception (evaluate)
import qualified Data.Map as Map
import Data.List
mapping :: Map.Map Int String
mapping = Map.fromList [
(1, "I"),
(4, "IV"),
(5, "V"),
(9, "IX"),
(10, "X")]
keys :: [Int]
keys = (reverse . sort . Map.keys $ mapping)
largestReducer :: Int -> [Int] -> Int
largestReducer number = foldr1 (\x acc -> if x <= number then x else acc)
convert :: Int -> String
convert x
| x == 0 = ""
| otherwise = convertedString ++ convert (x - reducer)
where reducer = largestReducer x keys
convertedString = case (Map.lookup reducer mapping) of
Just value -> value
Nothing -> ""
main :: IO ()
main = hspec $ do
describe "Roman Numerals" $ do
it "finds the largest reducer" $ do
largestReducer 11 keys `shouldBe` 10
largestReducer 10 keys `shouldBe` 10
largestReducer 9 keys `shouldBe` 9
largestReducer 8 keys `shouldBe` 5
largestReducer 4 keys `shouldBe` 4
it "converts Arabic to Roman" $ do
convert 1 `shouldBe` "I"
convert 2 `shouldBe` "II"
convert 4 `shouldBe` "IV"
convert 8 `shouldBe` "VIII"
convert 11 `shouldBe` "XI"
convert 15 `shouldBe` "XV"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment