Reputation: 299
I have a list with elements of a type that has multiple constructors (e.g. something like this). How can I extract element(s) of the list that match a particular constructor?
One way I could figure out was using list comprehension. E.g. given a list fields
with elements of type Field
from above example, I could extract the first From
field:
from = head [head f | From f <- fields]
Is there a simpler way to do it?
Upvotes: 2
Views: 235
Reputation: 2382
To filter the list that match the From
constructor, you can use the filter
function:
filter (\x -> case x of From {} -> True; _ -> False) fields
and then take the head
to take the first element.
head . filter (\x -> case x of From {} -> True; _ -> False) $ fields
Upvotes: 1