I'm working on a piece of code where I have to process lists of tuples where both the order and names of the "keys" (fst
s of the tuples) match a certain template. I'm implementing fault tolerance by validating and (if needed) generating a valid list based on the input.
Here's an example of what I mean:
Given the template of keys, ["hello", "world", "this", "is", "a", "test"]
, and a list [("hello", Just 1), ("world", Just 2), ("test", Just 3)]
, passing it to my function validate
would cause it to fail validation - as the order and values of the keys do not match up with the template.
Upon failing validation, I want to generate a new list, which would look like [("hello", Just 1), ("world", Just 2), ("this", Nothing), ("is", Nothing), ("a", Nothing), ("test", Just 3)]
.
I tried performing this last step using an (incomplete) list comprehension:
[(x, y) | x <- template, y <- l]
(Obviously, this is missing the step where empty entries would be replaced with Nothing
s, and works under the assumption that the input is of type [(String, Maybe Int)]
).
What would be the easiest semantic way of doing this?
You essentially want to map a function to your list of strings (which you call "template"), i.e. the function that
xs
,(xs, Just n)
if an integern
is associated toxs
in your "list to validate",(xs, Nothing)
otherwise.Here is one possible approach:
However, you will get faster lookup if you build a
Map
holding the key-value pairs of your association list (the "list to validate"):In GHCi: