Definiton of length using foldr

前端 未结 3 1980
眼角桃花
眼角桃花 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 18:07

    First, type of foldr: (a -> b -> b) -> b -> [a] -> b

    Taking the usage into context, foldr takes in 3 arguments: a function (that takes in a. an element of a list and b. an accumulator, and returns the accumulator), the starting value of accumulator, and a list. foldr returns the final result of the accumulator after applying the function through the list.

    As for this piece of code:

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

    As you can see, it is missing the list - so the return value of the right hand side is a function that will take in a list and produce an Int (same type as 0). Type: [a] -> Int.

    As for what the right hand side means: (\_ n -> 1 + n) 0

    \ means declare an unnamed function

    _ means ignore the element from the list (correspond to a in the type of foldr). As you know, foldr will go through the list and apply the function to each element. This is the element passed into the function. We don't have any use of it in a length function, so we denote that it should be ignored.

    n is the parameter for the Int passed in as accumulator.

    -> means return

    1 + n will increment the accumulator. You can imagine that the return value is passed back to foldr and foldr saves the value to pass into the next call to the function (\_ n -> 1 + n).

    The 0 outside the bracket is the starting value of the counter.

提交回复
热议问题