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
4

1 に答える 1

7

の種類を見てみましょうfilter

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

のタイプniMatchNI -> Person -> Bool

Haskell はaと統合しますNIが、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より慣用的な Haskell アプローチを実行して、レコードとして保存してみましょう。

newtype Person = Person {
  ni :: NI,
  age :: Age,
  balance :: Balance
} deriving (Eq, Show)

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

自動生成されたゲッターを使用できるようになりました。

于 2013-10-07T05:37:00.577 に答える