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
Can someone explain me how this works? I can’t wrap my mind around it.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
First, type of
foldr:(a -> b -> b) -> b -> [a] -> bTaking the usage into context,
foldrtakes 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.foldrreturns the final result of the accumulator after applying the function through the list.As for this piece of code:
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 toain the type offoldr). As you know,foldrwill 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 alengthfunction, so we denote that it should be ignored.nis the parameter for the Int passed in as accumulator.->means return1 + nwill increment the accumulator. You can imagine that the return value is passed back tofoldrandfoldrsaves the value to pass into the next call to the function(\_ n -> 1 + n).The
0outside the bracket is the starting value of the counter.