哈斯克尔模式匹配列表的内容



我有一个元素列表:

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 函数呢?

这将起作用

getA theList = listToMaybe [x | A x <- theList]
getB theList = listToMaybe [x | B x <- theList]

您将需要导入Data.Maybe .

概括这是可能的,但很棘手。 你甚至希望这个函数具有什么类型? ([a]->somethingToRepresentAConstructor->Int)。

那么能够获取列表中任何指定构造函数的值的 getX 函数呢?

关于泛化,东西代表构造函数可能是一个字符串?

你可以再概括一点,得到

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

最新更新