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

Is there a good way to find the first occurrence of a constructor in a list without explicit recursion in the example below?

data Elem = A Int | B Char deriving Show getA :: [Elem] -> Maybe Elem getA [] = Nothing getA (e:es) = case e of A a -> Just (A a) _ -> getA es 
+8
haskell
source share
3 answers

Just

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

Application: even better, with the future, using an empty recording template (kudos hammar):

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

Note, however, that this works so neatly for matching constructors. For general properties, find better:

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

You can use Data.List.find .

 getA = find isA where isA (A {}) = True isA _ = False 
+11
source share

You can use find:

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

All Articles