2017-10-09 58 views
1

我最近开始学习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 
+0

'头部c'是一个字符。改用'[head c]'。与c一样! 1':应该是[c !! 1]'。 –

+1

请注意,这种编程风格效率低下('长度'扫描整个列表),危险的(像head,tail,!!这样的函数会在列表太短时使程序崩溃)和不正确的('romanToInt',如书面所示,总是返回'0')。我强烈建议你避免这种非惯用风格,并尝试利用模式匹配,这是更安全和更习惯。 – chi

回答

2

在Haskell,String[Char]的代名词。

c in romanToInt的类型为String,即[Char]

head的类型为[a] -> a,所以head c的类型为Char

(!)的类型是Ord k => Map k a -> k -> a。在这种情况下,mapRomantoInt的类型为Map String Int,因此k必须是String

但函数调用mapRomantoInt ! head c试图通过Char而不是[Char]String)。

OP中的代码还存在其他问题,但首先尝试修复编译错误。

+0

感谢您的回答!我已经改变了头c到[头c],它完美的工作! – ProPall

相关问题