3

我想知道如何从列表列表中过滤出整个列表

Example: [ ["Bob", "Baker", "male", "70000"],
         ["Alice", "Allen", "female", "82000"] ] 

现在我想过滤包含女性的列表。所以输出将是:

["Alice", "Allen", "female", "82000"]

谢谢

4

2 回答 2

8
Prelude> let a = [ ["Bob", "Baker", "male", "70000"], ["Alice", "Allen", "female", "82000"] ]
Prelude> filter (elem "female") a
[["Alice","Allen","female","82000"]]
于 2013-09-24T10:41:42.373 回答
8

Ankur 的回答肯定会解决您的问题,但我想提出一个可以让您的生活更轻松的建议。似乎您将所有数据作为字符串存储在列表中,但实际上您想要的是一种可以以更有条理的方式保存所有这些数据的数据类型,这可以使用 Haskell 数据类型来完成,例如:

data Person = Person {
    firstName :: String,
    lastName :: String,
    gender :: String,
    salary :: String
    } deriving (Eq, Show)

然后,您可以轻松地使用 对数据进行排序filter (("female" ==) . gender) a。虽然这是前面的更多代码,但稍后如果您要为“先生”、“夫人”等添加“标题”字段,那么将其添加为第一个字段还是最后一个字段,此代码仍然有效。此外,如果由于某种原因您有一个无效值,例如["Bob", "Baker", "male", "70000", "female"],Ankur 的解决方案会给您一个不正确的结果,但是使用自定义数据类型,这甚至不会编译。

您可以通过一些调整来进一步改进您的数据结构。我建议为性别创建一个数据类型,然后使用IntorDouble作为薪水字段,这样你就有了

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
于 2013-09-24T13:20:44.123 回答