gpt4 book ai didi

Haskell 类型错误与 where

转载 作者:行者123 更新时间:2023-12-04 18:08:58 25 4
gpt4 key购买 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

最佳答案

我们来看看filter的类型

filter :: (a -> Bool) -> [a]-> [a]
niMatch的类型是 NI -> Person -> Bool
所以 Haskell 统一了 aNI ,但是 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
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com