haskell - Tuple evaluation -
i'm writing function of following type:
match :: [(string,a)] -> maybe (string, a, a)
i want function traverse list of tuples, , determine if there tuples in first element (a string) same. if so, want return tuple containing string, second element in each of matching tuples. if there no matching tuples, return "nothing". if there more 1 matching, return first 1 finds.
for example:
match [("x", 3), ("y", 4), ("z", "5"), ("x", 6)] = ("x", 3, 6) match [("x", 3), ("y", 4), ("z", "5")] = nothing
i'm thinking:
match (x:xs) = if (fst x) = (fst xs) return (fst x, snd x, snd xs) --if no matches, return nothing
thank help!
what if there 3 or 4 tuples "x"? can't have variable-length tuples. maybe want return list:
match :: [(string, a)] -> maybe (string, [a])
what if there several tuples match? want them all, or first? if want them should return list of matches.
match :: [(string, a)] -> [(string, [a])]
if think of this, can see grouping "x" pairs together, , "y" pairs, , on, start. can using
sortby (comparing fst) xs
comparing
takes function , 2 values, applies function each, , compares results. sortby
uses first argument comparison function, sortby (comparing fst)
sorts list order first element in each tuple.
then can use groupby
collect elements together.
edit:
groupby
has type
groupby :: (a -> -> bool) -> [a] -> [[a]]
so need write function equalfirst
give parameter.
groupby equalfirst $ sortby (comparing fst) xs
will give you
[[("x", 3), ("x", 6)], [("y", 4)], [("z", 5)]]
which list of lists. each sub-list contains tuples same letter.
now can write function takes 1 of these sublists , converts result want. apply list of lists using map
.
Comments
Post a Comment