Haskell higher order function to calculate length

穿精又带淫゛_ 提交于 2019-12-12 02:53:44

问题


I can't understand what's happening here? Can anybody please explain this code? How does this function calculate the length?

callength = foldr (\_ n -> 1 + n) 0

Why does it use lambda, underscore, space between underscore and n and zero on the right hand side?


回答1:


(\_ n -> 1 + n) simply means a function that takes two arguments, and returns one more than its second argument. The underscore simply means that a parameter is ignored. For comparison, as a top-level declaration without using a wildcard pattern (the underscore), this function would look like:

foo x n = 1 + n

Now, here's an example list:

[1, 2, 3, 4]

This is actually just syntactic sugar for:

1 : 2 : 3 : 4 : []

What foldr does is recursively replace each (:) with the function it's given, and the [] with the argument after the function (the zero). So, foldr f z [1, 2, 3, 4] for any f and z looks like this:

f 1 (f 2 (f 3 (f 4 z)))

(This is why foldr (:) [] just returns back the same list you give it — it ends up reconstructing the original list structure.)

In this case, using the function foo and the zero 0, it looks like:

foo 1 (foo 2 (foo 3 (foo 4 0)))

We know that foo ignores its first argument, and returns one more than its second argument. So this is the same as:

1 + (1 + (1 + (1 + 0)))

which is 4, the length of the list. Basically, the fold ignores every element of the list, and just adds one to an accumulator for every element, giving the length. The 0 is used to end the whole process, and because the length of the empty list is 0.

To see this in more detail, we can expand each call step-by-step:

foldr foo 0 (1 : 2 : 3 : 4 : [])
foo 1 (foldr foo 0 (2 : 3 : 4 : []))
1 + foldr foo 0 (2 : 3 : 4 : [])
1 + foo 2 (foldr foo 0 (3 : 4 : []))
1 + 1 + foldr foo 0 (3 : 4 : [])
1 + 1 + foo 3 (foldr foo 0 (4 : []))
1 + 1 + 1 + foldr foo 0 (4 : [])
1 + 1 + 1 + foo 4 (foldr foo 0 [])
1 + 1 + 1 + 1 + foldr foo 0 []
1 + 1 + 1 + 1 + 0
1 + 1 + 1 + 1
1 + 1 + 2
1 + 3
4


来源:https://stackoverflow.com/questions/9297320/haskell-higher-order-function-to-calculate-length

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!