Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.