Haskell 哈斯克尔:如何获得指定类型的人物列表?
我的用户数据类型如下Haskell 哈斯克尔:如何获得指定类型的人物列表?,haskell,types,tuples,Haskell,Types,Tuples,我的用户数据类型如下 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] databa
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))]
那么如何从中获取指定类型的图形呢?声明一个谓词,如
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
这样您就可以有一个类型安全的圆(或矩形等)列表:
注意:是从。列表理解也有效
[ s | s@(Circle _ _) <- database ]
[s|s@(圆)术语注释:形状
是一种类型。圆
、矩形
、三角形
和标签
是构造函数。列表只能包含单一类型的值。
[ s | s@(Circle _ _) <- database ]