簡體   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