求解

``````romeNotation :: [String]
romeNotation =
["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]

romeAmount :: [Int]
romeAmount = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]

pair :: [(Int, String)]
pair = zip romeAmount romeNotation
``````

``````subtrahend :: Int -> (Int, String)
subtrahend n = head (dropWhile (\(a, _) -> a > n) pair)
``````

``````> subtrahend 5
(5,"V")
> subtrahend 86
(50,"L")
``````

``````convert :: Int -> String
convert 0 = ""
convert n = let (rome, m) = subtrahend n in m ++ convert (n - rome)

> convert 12
"XII"
> convert 109
"CIX"
> convert 1925
"MCMXXV"
> convert 4567
"MMMMDLXVII"
``````

``````  convert 17
= "X" ++ convert (17 - 10)
= "X" ++ "V" ++ convert (7 - 5)
= "X" ++ "V" ++ "I" convert (2 - 1)
= "X" ++ "V" ++ "I" ++ "I" convert (1 - 1)
= "X" ++ "V" ++ "I" ++ "I" ++ ""
= "XVII"
``````

扩展

``````import           Data.List
import           Data.Maybe

subtrahend' :: String -> (Int, String)
subtrahend' n = head (dropWhile (\(_, a) -> not (a `isPrefixOf` n)) pair)

convert' :: String -> Int
convert' [] = 0
convert' n =
let (rome, m) = subtrahend' n
in  rome + convert' (fromMaybe "" (stripPrefix m n))

> convert' "XII"
12
> convert' "CIX"
109
> convert' "MCMXXV"
1925
> convert' "MMMMDLXVII"
4567
``````

后记

"To iterate is human, to recur, divine." - L. Peter Deutsch

推荐阅读更多精彩内容

• 第2章 基本语法 2.1 概述 基本句法和变量 语句 JavaScript程序的执行单位为行（line），也就是一...
泰迪学长_阅读 1,735评论 0 12
• pdf下载地址：Java面试宝典 第一章内容介绍 20 第二章JavaSE基础 21 一、Java面向对象 21 ...
王震阳阅读 73,514评论 25 504
• ES6 http://es6.ruanyifeng.com 目录 1 let 和 const 命令 2 变量的解构...
常青1890阅读 4,969评论 0 41
• Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
苏黎九歌阅读 5,674评论 0 38
• 很多人问我，刚上大三，为什么会选择去新疆支教？ 我说：因为迷茫。 大学迷茫现象已经泛滥成灾，而我也没有成为漏网之人...
007王小草阅读 14评论 0 1