Haskell Type error with where -


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     nimatch n (a,_,_)          | n ==    =   true         | otherwise =   false 

when run function type error

couldnt match type (person, t0, t1) -> bool bool 

however when make own function works

personnimatchs :: ni -> person -> bool personnimatchs n (a,_,_)      | n ==    =   true     | otherwise =   false 

let's @ type of filter

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

the type of nimatch ni -> person -> bool

so haskell unifies a ni, person -> bool doesn't work! that's not bool, hence confusing error message. see visually haskell unifying

     -> bool -- ^      ^ unification error!    ni  -> (person -> bool)  

now assume type bank = [person] want

 sumallaccounts n = sum . map getbalance . filter matchni    matchni (a, _, _) = == n          getbalance (_, _, b) = b  -- i've added code here sum balances here  -- without it, you're returning bank of persons accounts. 

but can make better! let's more idiomatic haskell approach , store person record.

newtype person = person {   ni :: ni,   age :: age,   balance :: balance } deriving (eq, show)  sumallaccounts :: ni -> bank -> balance sumallaccounts n = sum . map balance . filter ((==n) . ni) 

much neater, can use autogenerated getters.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -

php - Accessing static methods using newly created $obj or using class Name -