有人可以解释下面的代码如何工作?

时间:2016-10-04 05:49:13

标签: haskell

我无法弄清楚两个递归(myMaximumBy)是如何协同工作的,而我正在尝试在纸上绘制图表但是我被卡住了。例如,myMaximumBy比较[1,5,2,4,3]

myMaximumBy :: (a -> a -> Ordering) -> [a] -> a
myMaximumBy _ (x:[]) = x
myMaximumBy f (x:xs) = if (f x (myMaximumBy f xs)) == GT then x else (myMaximumBy f xs)

1 个答案:

答案 0 :(得分:2)

基本上你遍历整个列表,直到你击中一个元素x(第一行)。由于x是唯一的元素,因此必须是maxium。

现在你向后检查每个元素y与x:如果y大于x(第一种情况),那么你继续用y作为最大值,否则你保持x(第二种情况)。

我不会将你的定义与if子句一起使用,而是使用maxBy来说明这一点:

maximumBy f [x] = x
maximumBy f (x:xs) = maxBy f x (maximumBy f xs)

maxBy f x y | f x y == GT = x
            | otherwise   = y

此定义与您的定义相同。

示例:

maximumBy (comparing abs) [2,5,-3,1]
== maxBy (comparing abs) 2 (maxBy (comparing abs) 5 (maxBy (comparing abs) -3 (maximumBy (comparing abs) [1])))
== maxBy (comparing abs) 2 (maxBy (comparing abs) 5 (maxBy (comparing abs) -3 1))
== maxBy (comparing abs) 2 (maxBy (comparing abs) 5 -3)
== maxBy (comparing abs) 2 5
== 5