kruipen
kruipen

Reputation: 299

Pattern matching on elements of a list

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

Answers (1)

tofcoder
tofcoder

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

Related Questions