Question

data SomeData = A Int
              | B Int
              | C Int

list :: [SomeData]
list = [ A 1, B 2, C 3]

wantedData = filter (?) list -- wantedData is A 1

For the code above, what function should I put in (?) so that I get the desired data?

Was it helpful?

Solution

If you only want the list to contain A values then this should work as your predicate:

isA (A _) = True
isA _ = False

It's just pattern matching.

OTHER TIPS

Something closer to the ability to write an anonymous function, and not having to define a new function, is a list comprehension.

For example, you can say

list = [ A 1, B 2, C 3]

wantedData = [ A n | A n <- list ] -- result: [A 1]

Another possibility:

data SomeData = A Int | B Int | C Int
                            deriving (Show, Read, Eq)

list :: [SomeData]
list = [ A 1, B 2, C 3 ]

wantedData :: [SomeData]
wantedData = filter (== A 1) list             -- wantedData is A 1

Test:

> wantedData 
> [A 1]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top