Idiomatic way to fetch the first occurrence of a specific constructor from a list

Simply

import Data.Maybe (listToMaybe)
getA xs = listToMaybe [e | e@(A _) <- xs]

Addendum: even better, future-proofed using an empty record pattern (kudos hammar):

getA xs = listToMaybe [e | e@(A{}) <- xs]

Note however, that this only works out so neatly for matching constructors. For general properties, find is nicer:

get prop xs = listToMaybe [e | e <- xs, prop e]
get prop xs = listToMaybe (filter prop xs)
get prop xs = find prop xs

You can use Data.List.find.

getA = find isA
   where isA (A {}) = True
         isA _ = False

You could use find:

data Elem = A Int | B Char deriving Show
getA elements = find (\x->case x of (A _) -> True; _ -> False) elements

Tags:

Haskell