adding data to list
say i had a list where i wanted to add name and age so [(String,Int)] to the table but if the name already existed it would change the age. How would i go about doing this???
Technically this isn't homework as this is nothing like the question i have bee开发者_如何学Cn given but as it will help me understand the question i have been given then i will put the h/w tab on it
If I understood your question right, you want a function, that takes a (String,Int)
and a [(String,Int)]
and
- if the name is already contained inside the list, just update the age
- else, attach the name to the list.
We use recursion here. Each element of the list is passed through kind of a filter, which checks whether the name is equal for every element of the list, until it is equal or we reach the end of the list. In the first case, the age is altered and the rest of the list is attached to it, in the second case we attach a new element to the list:
-- This is a type signature. If you don't know what this is, just skip it.
alterList :: (String,Int) -> [(String,Int)] -> [(String,Int)]
alterList record [] = [record] -- If the list is empty, add our name
alterList record@(name,age) (x@(name',_):xs)
| name == name' = record : xs -- If the naame exists, alter and we're done
| otherwise = x : alterList record xs -- If not, iterate
However, it's only good to represent such data as a list, if you want to stream it. Usually, you may want to use a Map
instead. It provides a good support for key-value data, with great performance and sharing of modified components.
精彩评论