2013-10-07 49 views
5
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 
+0

請包括'Bank'的定義。 – luqui

回答

7

讓我們來看看類型filter

filter :: (a -> Bool) -> [a]-> [a] 

niMatchNI -> Person -> Bool

所以哈斯克爾統一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. 

但我們才能做得更好!讓我們做更習慣性的哈斯克爾方法,並將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) 

很整潔,現在我們可以使用自動生成的獲得者。