简体   繁体   English

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

[英]Can someone explain how the code below works?

I can't figure out how two recursions(myMaximumBy) work together, and I'm trying to draw diagram on paper but I'm stuck.我无法弄清楚两个递归(myMaximumBy)如何一起工作,我试图在纸上绘制图表但我被卡住了。 For example, myMaximumBy compare [1, 5, 2, 4, 3]例如,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)

Basically you traverse the entire list until you hit a single element, x (first line).基本上,您遍历整个列表,直到遇到单个元素 x(第一行)。 Since x is the only element, it must be the maxiumum.因为 x 是唯一的元素,所以它一定是最大值。

Now you go backwards and check every element y against x: If y is greater than x (first case) then you continue with y as your maximum, otherwise you keep x (second case).现在您倒退并根据 x 检查每个元素 y:如果 y 大于 x(第一种情况),则继续将 y 作为最大值,否则保留 x(第二种情况)。

Instead of using your definition with the if-clause I will use maxBy to illustrate this:我将使用maxBy来说明这一点,而不是将您的定义与 if 子句一起使用:

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

This definition is equivalent to yours.这个定义和你的一样。

Example:例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM