考虑以下示例:
data TestType = Free | Occupied { oc_field1 :: Int,
oc_field2 :: Int,
oc_field3 :: Int,
oc_field4 :: Int
}
type SampleTest = [TestType]
filterOccupied :: SampleTest -> SampleTest
filterOccupied test = filter (\x -> case x of
Occupied _ _ _ _ -> True
Free -> False ) test
在上面的示例中,在filterOccupied内部,我必须使用四个_
来匹配Occupied
类型。
当记录超过十个字段时,这变得非常痛苦。有更好的方法吗?
答案 0 :(得分:5)
您可以使用{}
模式。
filterOccupied :: SampleTest -> SampleTest
filterOccupied test = filter (\x -> case x of
Occupied {} -> True
Free -> False ) test
答案 1 :(得分:3)
添加到snak的答案,使用列表理解也可能更容易:
filterOccupied :: SampleTest -> SampleTest
filterOccupied test = [x | x@(Occupied {}) <- test]
只有与该模式匹配的项目才会保留在列表中。
答案 2 :(得分:0)
怎么样:
data TestType = Free
| Occupied { oc_field1 :: Int
, oc_field2 :: Int
, oc_field3 :: Int
, oc_field4 :: Int
}
deriving Eq
filterOccupied :: [TestType] -> [TestType]
filterOccupied = filter (Free/=)