繁体   English   中英

无法将Char类型与Haskell的[Char]相匹配

[英]Couldn't match type Char with [Char], Haskell

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

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

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

head的类型为[a] -> a ,因此head c的类型为Char

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM