[英]confused about haskell function to get length of list
I am going through the school of haskell basics and on the functions on lists section it uses this expression to get the length of the list我正在学习 haskell基础知识和列表部分的函数,它使用此表达式来获取列表的长度
intListLength (_:xs) = 1 + intListLength xs
I have tried manipulating this with different values where the one is and it seems to be multiplying even though the expression is with addition although the function is returning the correct value for the length of the list.我已经尝试用不同的值来操作它,即使表达式是加法的,它似乎也在相乘,尽管 function 正在返回列表长度的正确值。
I was hoping someone would be able to explain what's happening here.我希望有人能够解释这里发生了什么。
intListLength :: [Integer] -> Integer
intListLength [] = 0
intListLength (x:xs) = 1 + intListLength xs
As the document you linked explains:正如您链接的文档所解释的那样:
The first clause says that the length of an empty list is 0. The second clause says that if the input list looks like (x:xs), that is, a first element xconsed onto a remaining list xs, then the length is one more than the length of xs.
第一个子句说空列表的长度为 0。第二个子句说如果输入列表看起来像 (x:xs),即第一个元素 xconsed 到剩余的列表 xs 上,那么长度是多一个比 xs 的长度。
Since we don't use x at all we could also replace it by an underscore: intListLength (_:xs) = 1 + intListLength xs.
由于我们根本不使用 x,我们也可以用下划线替换它:intListLength (_:xs) = 1 + intListLength xs。
The function intListLength
is adding 1
to a running sum for every element in the list. function
intListLength
将列表中每个元素的运行总和加1
。 Every time intListLength
is called, an element is popped off the list, and a 1
is added to a running total created by the recursive call on the remaining elements of the list.每次调用
intListLength
时,都会从列表中弹出一个元素,并将1
添加到由对列表剩余元素的递归调用创建的运行总数中。 When there are no more elements in the list, the empty list function head is matched and a 0
is added to the total.当列表中没有更多元素时,匹配空列表 function 头部并在总数中添加一个
0
。 At that point, the total is returned.此时,将返回总数。
intListLength (_:xs) = 1 + intListLength xs
In plain English this means "the length of a list starting with any element ( _
) followed by the elements xs
is 1
plus then length of the list xs
".在简单的英语中,这意味着“列表的长度以任何元素 (
_
) 开头,后跟元素xs
是1
加上列表xs
的长度”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.