使用foldr确定长度 [英] Definiton of length using foldr
问题描述
length = foldr(\_ n - > 1 + n)0
有人能解释我是如何工作的吗?
首先,键入 foldr
:(a - > b - > b) - > b - > [a] - > b
将用法应用到上下文中, foldr
需要3个参数:一个函数(它接收 a。列表元素和 b。累加器,并返回累加器),累加器的起始值和列表。 foldr
通过列表应用函数后返回累加器的最终结果。
至于这段代码:
length = foldr(\_ n - > 1 + n)0
$ c $正如你所看到的那样,它缺少列表 - 所以右边的返回值是一个函数,它将包含一个列表并且产生一个Int(与 0
相同)。类型: [a] - > Int
。
至于右手边的含义:(\_ n - > 1 + n )0
\
表示声明一个未命名的函数
_
表示忽略列表中的元素(对应于类型中的 a
) foldr
)。如您所知, foldr
将会遍历列表并将函数应用于每个元素。这是传递给函数的元素。我们没有在长度
函数中使用它,所以我们表示应该忽略它。
n
是作为累加器传入的Int参数。
- >
表示返回
1 + n
会累加累加器。你可以想象,返回值被传回给 foldr
,并且 foldr
保存要传递给下一次调用的值(\_ n - > 1 + n)
。
0
括号外是计数器的起始值。
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.
解决方案 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.
这篇关于使用foldr确定长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!