考虑以下示例:
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
类型。当记录具有十个以上字段时,这变得非常痛苦。有一个更好的方法吗 ?
最佳答案
您可以改用{}
模式。
filterOccupied :: SampleTest -> SampleTest
filterOccupied test = filter (\x -> case x of
Occupied {} -> True
Free -> False ) test