sách gpt4 ai đã đi

Haskell 类型错误与 where

In lại 作者:行者123 更新时间:2023-12-04 18:08:58 25 4
mua khóa gpt4 Nike

type NI = Int
type Age = Int
type Balance = Int
type Person = (NI, Age, Balance)
type Bank = [Person]


sumAllAccounts :: NI -> Bank -> Int
sumAllAccounts n l = filter niMatch l
where niMatch n (a,_,_)
| n == a = True
| otherwise = False

当我运行这个函数时,我收到一个类型错误
couldnt match type (Person, t0, t1) -> Bool with Bool

但是,当我创建它自己的功能时,它可以工作
personNIMatchs :: NI -> Person -> Bool
personNIMatchs n (a,_,_)
| n == a = True
| otherwise = False

1 Câu trả lời

我们来看看filter的类型

filter :: (a -> Bool) -> [a]-> [a]
niMatch的类型是 NI -> Person -> Bool
所以 Haskell 统一了 MộtNI ,但是 Person -> Bool不起作用!那不是 Bool ,因此您的错误消息有些令人困惑。从视觉上看 Haskell 是统一的
   a -> Bool
-- ^ ^ unification error!
NI -> (Person -> Bool)

现在我假设 type Bank = [Person]那么你只想要
 sumAllAccounts n = sum . map getBalance . filter matchNI
where matchNI (a, _, _) = a == n
getBalance (_, _, b) = b
-- I've added the code here to actually sum the balances here
-- without it, you're returning a Bank of all a persons accounts.

但我们可以做得更好!让我们做更惯用的 Haskell 方法和存储 Person作为记录。
newtype Person = Person {
ni :: NI,
age :: Age,
balance :: Balance
} deriving (Eq, Show)

sumAllAccounts :: NI -> Bank -> Balance
sumAllAccounts n = sum . map balance . filter ((==n) . ni)

更简洁,现在我们可以使用自动生成的 getter。

关于Haskell 类型错误与 where,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19217646/

25 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com