Last active
August 29, 2015 14:16
-
-
Save davidallsopp/214e2700d713d6bcdc7f to your computer and use it in GitHub Desktop.
Parsing roman numerals in Haskell - from http://rosettacode.org/wiki/Roman_numerals/Decode#Haskell. See also https://gist.github.com/davidallsopp/ee1c52a32ed9da393529
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Data.List (isPrefixOf) | |
numerals = [("M",1000),("CM",900),("D",500),("CD",400),("C",100),("XC",90), | |
("L",50),("XL",40),("X",10),("IX",9),("V",5),("IV",4),("I",1)] | |
toArabic :: String -> Int | |
toArabic "" = 0 | |
toArabic str = num + toArabic xs | |
where (num, xs):_ = [ (num, drop (length n) str) | (n,num) <- numerals, isPrefixOf n str ] | |
-- Seems gratuitously unclear for the sake of a one-liner. How about: | |
toArabic2 :: String -> Int | |
toArabic2 "" = 0 | |
toArabic2 str = n + toArabic xs | |
where xs = drop (length ch) str | |
Just (ch, n) = find ((`isPrefixOf` str) . fst ) numerals |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
:_ =
pattern match is the same as taking thehead
.