【问题标题】:Couldn't match type Char with [Char], Haskell无法将 Char 类型与 [Char] 匹配,Haskell
【发布时间】: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


【解决方案1】:

在 Haskell 中,String 是 [Char] 的同义词。

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

head 的类型是[a] -&gt; a,所以head c 的类型是Char。

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

然而,函数调用 mapRomantoInt ! head c 尝试传递 Char 而不是 [Char] (String)。

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

【讨论】:

  • 感谢您的回答!我已将 head c 更改为 [head c] 并且效果很好!
猜你喜欢
  • 2022-01-23
  • 2021-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-08
  • 2014-08-30
相关资源
最近更新 更多