I would like to know how to filter a whole list out of list of lists
Example: [ ["Bob", "Baker", "male", "70000"],
["Alice", "Allen", "female", "82000"] ]
And now I would like to filter the list which contains female. So output would be:
["Alice", "Allen", "female", "82000"]
Thanks
Ankur's answer will certainly solve your problem, but I would like to make a suggestion that could make your life easier. It seems that you're storing all your data as strings in lists, but really what you'd like is a data type that could hold all this data in a more organized fashion, which can be done using Haskell data types, something like:
data Person = Person {
firstName :: String,
lastName :: String,
gender :: String,
salary :: String
} deriving (Eq, Show)
Then you could easily sort your data with filter (("female" ==) . gender) a
. While this is a bit more code up front, later on if you were to add a "title" field for "Mr", "Mrs", etc, then it wouldn't matter if you added it at as the first field or the last field, this code would still work. Also, if for whatever reason you had an invalid value like ["Bob", "Baker", "male", "70000", "female"]
, Ankur's solution would give you an incorrect result, but with a custom data type, this would not even compile.
You could further improve your data structure with a few tweaks. I would suggest making a data type for gender, and then use Int
or Double
for the salary field, so you would have
data Gender = Male | Female deriving (Eq, Show, Read)
data Person = Person {
firstName :: String,
lastName :: String,
gender :: Gender,
salary :: Int
} deriving (Eq, Show)
filtGender :: Gender -> [Person] -> [Person]
filtGender gend people = filter ((gend ==) . gender) people
main :: IO ()
main = do
let people = [Person "Bob" "Baker" Male 70000,
Person "Alice" "Allen" Female 82000]
putStr "The females are: "
print $ filtGender Female people
putStr "The males are: "
print $ filtGender Male people
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments