Home > other >  Find element in list in bind result?
Find element in list in bind result?

Time:09-23

Say I have the list [("sd", 55), ("s", 2), ("fgff", 23), ("s", 999)]. How can I find the first occurrence of ("s", v) and bind v to the associated value? So for example someFunc "s" mylist would return 2. Optimally I would be able to pattern match and do ("s", v) = ...

I am aware that I just could create a recursive function that itself uses pattern matching but I am looking for a more concise way that utilizes the already-defined functions of Haskell, like those in the standard prelude:))

CodePudding user response:

I assume you know that the entry exists in your list l. In that case you could use a list comprehension:

v = head[v | ("s", v) <- l] 

Alternatively (and the way I'd prefer) there is lookup which basically interprets a list of pairs as a dictionary, with the first entry as the key and the second entry ad the corresponding value:

Just v = lookup "s" l 

Note that the lookup return value is wrapped in a Maybe to handle the case that the value does not exist.

  • Related