2010-10-18 85 views
2

我做的:类型的错误

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" 

为什么我得到这个错误,我怎么能解决它?

+4

此外,你可以(也应该,这是毫无意义和困惑)放弃功能调用的parens。 – delnan 2010-10-18 11:40:26

回答

6

你的类型的签名应该是:

addOneToElement :: [Char] -> [Char] 

(或者更简单地说,addOneToElement :: String -> String

的 “a” 在您的类型签名是一个通配符 - 它可以匹配任何东西。但是,您试图将Char列表连接到任何列表 - 并且没有办法做到这一点。

+0

谢谢,我明白了。 – demas 2010-10-18 11:29:21

+1

当你说数组时,你的意思是列表。 – sepp2k 2010-10-18 11:29:49

+0

干杯,固定。我是白天的C++程序员,我的手指在自动驾驶。 – stusmith 2010-10-18 11:34:36

1

为什么你在这里使用类型变量呢?由于(++)的第二个操作数固定为[Char]"next"),所以可以与匹配的唯一类型是Char