【发布时间】:2017-10-09 08:04:20
【问题描述】:
我最近开始学习 Haskell,但遇到了字典问题。我使用一个键从字典中获取整数,而 GHCi 在我使用字符串的第一个元素作为字典键的行上打印错误“无法将类型 Char 与 [Char] 匹配”。代码如下:
import Data.Map
mapRomantoInt :: Map String Int
mapRomantoInt = fromList[("I",1),("V",5),("IX",9),("X",10),("L",50),("C",100),("D",500),("M",1000)]
romanToInt :: String -> Int
romanToInt _ = 0
romanToInt c = if length c == 1 then mapRomantoInt ! head c else
let first = mapRomantoInt ! head c
second = mapRomantoInt ! (c !! 1)
others = romanToInt(tail c)
in if first < second then others - first else others + first
【问题讨论】:
-
head c是一个字符。请改用[head c]。与c !! 1相同:应该是[c !! 1]。 -
请注意,这种编程风格既低效(
length扫描整个列表)、危险(head, tail, !!之类的函数会在列表太短时使程序崩溃)和错误(@987654328 @,如所写,总是返回0)。我强烈建议您避免这种非惯用风格,并尝试利用模式匹配,这样更安全、更惯用。
标签: haskell