Haskell beginner here.
I have a list of tuples type (a, b)
like so: [(1, "One"), (2, "2")]
, and a single pair (key, value)
.
I want to create a recursive function that accepts a pair and a list of tuples all type (a, b)
and returns the list after replacing all values associated to the passed key with the passed value:
changeTup :: (Eq a) => (a,b) -> [(a,b)] -> [(a,b)]
Example output:
> changeTup (1, "Hello") [(1, "One"), (2, "Two")]
=> [(1, "Hello"), (2, "Two")]
I did some digging and it seems like the best way to do this is with map
. I tried this but haven't gotten any good results.
This is my code:
changeTup :: (Eq a) => (a,b) -> [(a,b)] -> [(a,b)]
changeTup (y,z) [] = [(y,z)]
changeTup (y,z) (x:xs) = map replace
where replace (key, value)
| y == key = (key, z)
| otherwise = (key, value)
I'm not sure how to approach increments the list (x:xs)
within map
. I'm getting an expected type error
.
CodePudding user response:
The thing about the map
function is that iterating over a list (or another vaguely list-shaped thing) is its entire job. In the code you have, you have a perfectly fine replace
function, and you want to apply to the elements of the list (x : xs)
- and doing that is as simple as map replace (x : xs)