我最近开始学习Haskell,并且遇到了字典问题。我使用一个键从字典中获取整数,GHCi在字符串中使用第一个元素作为字典的键时,打印出一个错误“无法与类型Char匹配[Char]”。下面是代码:无法将类型Char与[Char]匹配,Haskell
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
'头部c'是一个字符。改用'[head c]'。与c一样! 1':应该是[c !! 1]'。 –
请注意,这种编程风格效率低下('长度'扫描整个列表),危险的(像head,tail,!!这样的函数会在列表太短时使程序崩溃)和不正确的('romanToInt',如书面所示,总是返回'0')。我强烈建议你避免这种非惯用风格,并尝试利用模式匹配,这是更安全和更习惯。 – chi