简体   繁体   English

func声明中键入错误

[英]type error in func declaration

I do: 我做:

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

But such code: 但是这样的代码:

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

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

produces this output: 产生这个输出:

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"

Why I get this error and how I can fix it? 为什么会出现此错误以及如何解决?

Your type signature should be: 您的类型签名应为:

addOneToElement :: [Char] -> [Char]

(Or more simply, addOneToElement :: String -> String ) (或更简单地说, addOneToElement :: String -> String

The " a " in your type signature is a wildcard - it can match anything. 类型签名中的“ a ”是通配符-它可以匹配任何内容。 However you are trying to concatenate a list of Char to a list of anything - and there is no way to do that. 但是,您正在尝试将Char列表连接到任何内容的列表中-并且无法做到这一点。

Why are you using a type variable here anyway? 您为什么仍然在这里使用类型变量? The only type that can match is Char , since the second operand of (++) is fixed to [Char] ( "next" ). 唯一可以匹配的类型是Char ,因为(++)的第二个操作数固定为[Char]"next" )。

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

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