繁体   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