簡體   English   中英

func聲明中鍵入錯誤

[英]type error in func declaration

我做:

Prelude> "sone" ++ "otehr"
"soneotehr"

但是這樣的代碼:

addOneToElement :: [a] -> [a]
addOneToElement element = element ++ "next"

main = do
   let s = addOneToElement("some")
   putStrLn s

產生這個輸出:

all_possible_combinations.hs:22:37:
    Couldn't match expected type `a' against inferred type `Char'
      `a' is a rigid type variable bound by
          the type signature for `addOneToElement'
            at all_possible_combinations.hs:21:20
      Expected type: [a]
      Inferred type: [Char]
    In the second argument of `(++)', namely `"next"'
    In the expression: element ++ "next"

為什么會出現此錯誤以及如何解決?

您的類型簽名應為:

addOneToElement :: [Char] -> [Char]

(或更簡單地說, addOneToElement :: String -> String

類型簽名中的“ a ”是通配符-它可以匹配任何內容。 但是,您正在嘗試將Char列表連接到任何內容的列表中-並且無法做到這一點。

您為什么仍然在這里使用類型變量? 唯一可以匹配的類型是Char ,因為(++)的第二個操作數固定為[Char]"next" )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM