我有一个元素列表:
data Foo = A Int | B Int | C Int
myList :: [Foo]
myList = [A 1, B 2, C 3]
我想要一个获取特定构造函数值的函数(如果存在的话):
-- returns value of the first A constructor, if exists:
getA :: [Foo] -> Maybe Int
-- returns value of the first B constructor, if exists:
getB :: [Foo] -> Maybe Int
任何优雅的解决方案?
那个getX
函数怎么样,能够获取列表中任何指定构造函数的值?
答案 0 :(得分:3)
这将有效
getA theList = listToMaybe [x | A x <- theList]
getB theList = listToMaybe [x | B x <- theList]
您需要导入Data.Maybe
。
概括这是可能的,但是很棘手......你甚至想要这个函数有什么类型? ([a]->somethingToRepresentAConstructor->Int
)。
答案 1 :(得分:1)
那么getX函数怎么样,能够获取列表中任何指定构造函数的值?
关于泛化,somethingToRepresentAConstructor可以是String?
您可以进一步概括并获得
firstJust :: (a -> Maybe b) -> [a] -> Maybe b
firstJust f xs = case filter isJust (map f xs) of
x : _ -> x
[] -> Nothing
getA = firstJust f
where f (A x) = Just x
f _ = Nothing
getB = firstJust f
where f (B x) = Just x
f _ = Nothing