cdupont
cdupont

Reputation: 1188

Haskell pattern match on content of list

I have a list of elements:

data Foo = A Int | B Int | C Int

myList :: [Foo]
myList = [A 1, B 2, C 3]

I want a function that gets the value of a specific constructor, if existing:

-- 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

Any elegant solution? And what about a getX function, capable of getting the value of any specified constructor in the list?

Upvotes: 2

Views: 898

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170713

And what about a getX function, capable of getting the value of any specified constructor in the list?

Regarding the generalization, the somethingToRepresentAConstructor could be a String?

You can generalize a bit more and get

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

Upvotes: 1

jamshidh
jamshidh

Reputation: 12060

This will work

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

You will need to import Data.Maybe.

Generalizing this would be possible, but tricky.... What type would you even want this function to have? ([a]->somethingToRepresentAConstructor->Int).

Upvotes: 3

Related Questions