gpt4 book ai didi

postgresql - 理解 Haskell postgresql 连接函数类型错误

转载 作者:行者123 更新时间:2023-11-29 12:22:46 25 4
gpt4 key购买 nike

我是 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 = ...

关于postgresql - 理解 Haskell postgresql 连接函数类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5690523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com