Understanding Haskell postgresql connection function type error
I am java programmer reading and learning haskell now. I am trying write a simple program to connect (and disconnect) to postgres database using HDBC postgres driver. For simplicity i don't have any other logic in it.
It is throwing a function type error. I indented the code correct and if I remove disconnect then it works with the defined type.
Can some one shed some light on what i am missing defining the type for this function? i would apriciate your help.
thanks!
sample code:
import Database.HDBC
import Database.HDBC.PostgreSQL
import Database.HaskellDB
import Database.HaskellDB.HDBC.PostgreSQL
tryConnect :: Int -> (Database -> IO Connection) -> ()
tryConnect id =
do
c <- postgresqlConnect [("host","dbhost"),("dbname","db1"),("user","开发者_Python百科user1"),("password","test")]
disconnect c
return ()
I am getting the following error from GHCi
Couldn't match expected type `(Database -> IO Connection) -> a'
against inferred type `IO ()'
In a stmt of a 'do' expression: disconnect c
In the expression:
do { c <- postgresqlConnect
[("host", "dbhost"), ("dbname", "db1"), ....];
disconnect c;
return () }
In the definition of `insrt':
insrt id
= do { c <- postgresqlConnect [("host", "dbhost"), ....];
disconnect c;
return () }
Failed, modules loaded: none.
The problem is that you haven't provided enough arguments to postgresqlConnect
. Its type signature is [(String, String)] -> (Database -> m a) -> m a
, but you've only provided the first argument. Giving postgresqlConnect
its second argument should solve the problem, and you'll be able to change the type declaration back to Int -> IO ()
.
EDIT: The answer below is totally wrong. My bad.
Well, the type signature is tryConnect :: Int -> (Database -> IO Connection) -> ()
. Generally this would indicate that the function takes an Int
and a (Database -> IO Connection)
and returns ()
, but the only parameter you've supplied in the function definition is id
. Therefore, you actually have a function that takes an Int
and returns a new function with the type signature (Database -> IO Connection) -> ()
.
This would be fine, except that the body of the function does not match this signature. The do
expression returns an IO ()
value rather than the expected function, so you get an error because the compiler got a different return value than expected.
So, to conclude, it seems there's a parameter in the type signature that you haven't used in the actual function. Either remove that function from the type signature, or change the function to be tryConnect id func = ...
rather than tryConnect id = ...
.
精彩评论