开发者

explain largestDivisible code from the Learn You A Haskell for Great Good tutorial

largestDivisible :: (Integral a) => a
largestDivisible = head (filter开发者_JAVA技巧 p [100000,99999..])
    where p x = x `mod` 3829 == 0

If p x equals True,

does

head (filter p [100000,99999..])

become

head (filter True)

?

What list is being filtered for True?

While this code is being run, what are p and x's values?


filter p [100000,99999..] calculates the list including all numbers descending from 100000 for which p returns true. head then takes the first of that list, effectively giving you the largest number x below 100000, for which p x returns true, i.e. for which x `mod` 3829 is 0.

What values are in p and x?

p is a function that takes one argument called x and returns true iff x `mod` 3829 == 0. x is the argument given to the function. Since you use p as an argument to filter, this means that each element of the list [100000,99999..] will be given to p in turn, until p returns true for the first time (it won't try any more elements because by using head, you're only requesting one element, so it only calculates one).


p is a function defined by p x = x `mod` 3829 == 0.

x is a variable in the p function. filter calls p with elements from the list [100000,99999..], so x will be one of the members of that list.

filter p [100000,99999..] is the same as (filter p) [100000,99999..], not filter (p [100000,99999..]). So p is not called with [100000,99999..] as an argument (and it would be a type error anyway).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜