了解Haskell PostgreSQL连接函数类型错误

| 我现在是Java程序员,正在阅读和学习haskell。我正在尝试编写一个简单的程序,以使用HDBC postgres驱动程序连接(和断开连接)到postgres数据库。为简单起见,我没有任何其他逻辑。 它抛出一个函数类型错误。我将代码缩进正确,如果删除断开连接,则它可以使用定义的类型。 有人可以阐明我为该函数定义的类型所缺少的吗?我会很感谢你的帮助。 谢谢! 样例代码:
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\",\"user1\"),(\"password\",\"test\")]
     disconnect c
     return ()
我从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 () }
失败,模块已加载:无。     
已邀请:
问题是您没有为
postgresqlConnect
提供足够的参数。它的类型签名是
[(String, String)] -> (Database -> m a) -> m a
,但是您只提供了第一个参数。给第二个参数
postgresqlConnect
应该可以解决问题,并且您可以将类型声明改回
Int -> IO ()
。 编辑:下面的答案是完全错误的。我的错。 好吧,类型签名是
tryConnect :: Int -> (Database -> IO Connection) -> ()
。通常,这表示该函数采用
Int
(Database -> IO Connection)
并返回
()
,但是您在函数定义中提供的唯一参数是
id
。因此,实际上您有一个函数,该函数需要
Int
并返回带有类型签名
(Database -> IO Connection) -> ()
的新函数。 可以,除非函数的主体与此签名不匹配。
do
表达式返回的是
IO ()
值而不是预期的函数,因此会出现错误,因为编译器获得的返回值与预期的不同。 因此,总而言之,似乎类型签名中有一个参数尚未在实际函数中使用。从类型签名中删除该函数,或者将函数更改为
tryConnect id func = ...
而不是
tryConnect id = ...
。     

要回复问题请先登录注册