Haskell中带参数的函数
我正在尝试编写一个函数,该函数有一个参数,您可以在其中指定希望从函数中获取的内容 示例:首先,我将使用以下功能创建一些形状:Haskell中带参数的函数,haskell,Haskell,我正在尝试编写一个函数,该函数有一个参数,您可以在其中指定希望从函数中获取的内容 示例:首先,我将使用以下功能创建一些形状: circle1 :: Radius -> Shape circle r = Shape (Circle r) circle2 :: Radius -> Shape circle2 r = Shape (Circle r) rectangle :: Side -> Side -> Shape rectangle x y = Shape (Rect
circle1 :: Radius -> Shape
circle r = Shape (Circle r)
circle2 :: Radius -> Shape
circle2 r = Shape (Circle r)
rectangle :: Side -> Side -> Shape
rectangle x y = Shape (Rectangle x y)
现在让我们假设我想要一个函数,在其中我可以指定我只想看到圆,我如何创建这样一个函数?因此,函数将如下所示:
getShapes(circle)
circle1
circle2
输出结果如下所示:
getShapes(circle)
circle1
circle2
首先,我想重组您的形状类型:
data Shape = Circle {r :: Double}
| Rectangle {l :: Double, w :: Double}
deriving (Show)
现在让我们考虑一下函数的类型,我认为它应该有两个输入,一个是我想要返回的形状的谓词,另一个是我选择的形状,所以
getShapes :: (Shape -> Bool) -> [Shapes] -> [Shapes]
这将是一个合理的选择-下一步-我们看到第二个函数(filter
)似乎适合我们的任务
getShapes = filter
因此,剩下的步骤是构建循环
-函数,通常称为谓词
如果您是haskell的新手-这里有haskell最强大的概念之一:模式匹配
circle(circle)
检查其参数是否具有类型circle
,其中类型类似于OO语言中的构造函数。\u
被称为I-don-care-variable,它在名称合适时使用。因此,圆检查它得到的形状是否是圆
,不关心它的半径,并返回真
-或-在任何其他情况下返回假
。
如果几周后我决定通过添加另一个Shape
data Shape = Circle {r :: Double}
| Rectangle {l :: Double, w :: Double}
| Ellipsis {a :: Double, b :: Double}
deriving (Show)
所以现在getShape circle[circle1,ellipsis1,circle2,rectangle1,rectangle2]
应该会产生
[circle1,circle2]
这就是你要找的吗
type Radius = Double
type Side = Double
data Shape = Circle Radius
| Rectangle Side Side
deriving (Show)
isCircle :: Shape -> Bool
isCircle (Circle _) = True
isCircle _ = False
circle1 :: Radius -> Shape
circle1 r = Circle r
circle2 :: Radius -> Shape
circle2 r = Circle r
rectangle :: Side -> Side -> Shape
rectangle x y = Rectangle x y
figures = [circle1 1.1, circle2 1.2, rectangle 1.3 1.4]
circles = filter isCircle figures
main = putStrLn $ show circles
请尝试在您的问题中给出所有定义和工作代码。