Definiton of length using foldr

前端 未结 3 1973
眼角桃花
眼角桃花 2021-02-04 17:09

I\'m trying to understand a part in the lecture notes of a class I\'m taking. It defines the length function as:

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


        
3条回答
  •  梦如初夏
    2021-02-04 17:51

    The function foldr is to fold the list with a right associative operator, you can easily understand what the function does if you use the operator(+), (The function has the same behavior as sum):

    foldr (+) 0 [1,2,3,4,5] = 1+(2+(3+(4+(5+0))))
    

    For your length function, it is equivalent to:

    foldr (\_ n -> 1 + n) 0 [1,2,3,4,5] = 1+(1+(1+(1+(1+0))))
    

    That is what the foldr for

提交回复
热议问题