我有像
这样的用户数据类型data Point = Point Float Float deriving (Show)
data Shape = Circle Point Float |
Rectangle Point Point |
Triangle Point Point Point |
Label Point Font String deriving (Show)
和数据库一样
database :: [Shape]
database = [(Circle (Point 2 5) 5), (Circle (Point 1 4) 3), (Circle (Point 8 3) 4),
(Rectangle (Point 0 5) (Point 10 0)), (Rectangle (Point 3 5) (Point 10 0)),(Rectangle (Point 0 10) (Point 20 0)),
(Triangle (Point 1 1) (Point 2 2) (Point 3 1)), (Triangle (Point 2 5) (Point 5 8) (Point 9 1))]
那么如何才能从中获得指定类型的数据?
答案 0 :(得分:2)
声明一个谓词,比如
isCircle :: Shape -> Bool
isCircle (Circle _ _) = True
isCircle _ = False
然后,按它过滤:
databaseCircles = filter isCircle database
但是,我建议你稍微分解你的类型:
data Circle = Circle Point Float
data Rectangle = Rectangle Point Point
data Triangle = Triangle Point Point Point
data Label = Label Point Font String
data Shape = CircleShape Circle | RectangleShape Rectangle
| TriangleShape Triangle | LabelShape Label
这样你就可以拥有一个类型安全的圆圈列表(或矩形等):
getMaybeCircle:: Shape -> Maybe Circle
getMaybeCircle (CircleShape c) = Just c
getMaybeCircle _ = Nothing
filterCircles :: [Shape] -> [Circle]
filterCircles = catMaybes . map getMaybeCircle
注意:catMaybes
来自Data.Maybe
。
答案 1 :(得分:0)
列表理解也有效
[ s | s@(Circle _ _) <- database ]