1

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 been given but as it will help me understand the question i have been given then i will put the h/w tab on it

0

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

@Ahsan Sorry. Typed too fast. If you have any questions about my function, please ask me.
sorry, its now showing this error Couldn't match expected type [(String, Int)]' against inferred type (String, Int)' In the expression: record In the definition of `alterList': alterList record [] = record
@Ahsan What it's saying is in the otherwise line FUZxxl should be calling alterList record xs (recursing properly) where as he is just applying xs - which isn't correct. I'll edit it.
@Ahsan If you don't know what the type signature is then I suggest you learn it, not skip it. Knowing the type signature you should clearly see that x : alterList xs is incorrect. X being of type (String,Int) and alterList xs is still a function needing another argument (actually, the first argument isn't even type correct).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.