从列表中获取特定构造函数的第一个匹配项的惯用方法

时间:2011-11-19 15:49:25

标签: haskell

有没有一种很好的方法可以在列表中找到第一次出现的构造函数,而下面的示例中没有显式的递归?

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

3 个答案:

答案 0 :(得分:11)

简单地

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

附录:更好,未来使用空记录模式(kudos hammar):

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

但请注意,这仅适用于匹配构造函数。对于一般属性,find更好:

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

答案 1 :(得分:11)

您可以使用Data.List.find

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

答案 2 :(得分:3)

您可以使用find:

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