如何在Haskell中实现函数内部?

时间:2015-11-09 22:49:32

标签: haskell

within :: (Ord a, Num a) => a -> [a] -> a

采用公差,即数字 epsilon和无限的数字列表,和 向下看列表,在列表中找到两个相差不超过epsilon的数字,它返回第二个数字。 (如果没有这样的一对,它可能永远不会返回 连续元素。)例如,

within 1.0 [1.0 ..] = 2.0
within 0.5 ([1.0, 32.5, 17.2346, 10.474, 8.29219, 8.00515]
++ [8.0, 8.0 ..])
= 8.00515

1 个答案:

答案 0 :(得分:5)

在Haskell中,列表只是另一种数据结构,可能有一些(在我看来)令人困惑的符号。使用任何数据结构,您都可以使用模式匹配。当您只使用列表时,模式中有三种可能的东西:

  • 变量,例如x
  • 应用于零个或多个模式的构造函数,
    • (:) x xs一样(或者更为家喻户晓:x:xs),
    • []

请注意,在模式中,您将构造函数应用于模式。编写(:) x ((:) y ys)(通常写为x:y:ys)是完全允许的,它匹配至少两个元素的任何列表,并将第一个元素分配给x,第二个元素分配给{{1} },以及列表的其余部分y

ys函数的骨架看起来像这样:

within

在这里,theFunction theList = case theList of x:y:ys -> if canGiveAnswer x y then buildAnswer x y else theFunction (y:ys) 尝试将其输入与模式theFunction进行匹配,检查x:y:ysx是否足以给出答案,并在可以的时候这样做,或者重新启动自身(y),删除列表的第一个元素。

你可以像

那样简洁地写出来
theFunction (y:ys)

甚至

theFunction (x:y:ys) = if canGiveAnswer x y then buildAnswer x y else theFunction (y:ys)

当然,在你的情况下,你需要一个额外的论点:

theFunction (x:y:ys) | canGiveAnswer x y = buildAnswer x y
                     | True = theFunction (y:ys)

我会让你知道within :: (Ord a, Num a) => a -> [a] -> a within epsilon (x:y:ys) | canGiveAnswer x y epsilon = buildAnswer x y epsilon | True = within epsilon (y:ys) canGiveAnswer应该是什么。

相关问题