如何用OCAML中的特定属性计数列表的记录?
可以说,我们有一个记录,该记录定义了具有属性名称>和
age
的人类型:
type person = {name:string ; age:int };;
并初始化具有不同类型的列表:
let personlist = [{name="alexander";age=21};{name="benjamin";age=30};{name="claudia";age=21}];;
我如何用可以说,特定的年龄21(亚历山大和克劳迪亚),以便在这种情况下的输出将是两个?
Lets say we have a record which defines a person type with the properties name
and age
:
type person = {name:string ; age:int };;
and initialize a list with different types:
let personlist = [{name="alexander";age=21};{name="benjamin";age=30};{name="claudia";age=21}];;
How can I count the amount of types with a specific age, lets say 21 (alexander and claudia) so that the output in this case would be two?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最直接的方法是组合
list.length
和list.filter
。但是,这效率不如可能。我们可以在一次通过中做到这一点,因为我们实际上不需要构建匹配的人的列表,然后迭代该列表以找到其长度。
list.fold_left
将让我们通过personList
进行迭代,在每次迭代中更新0
的初始值,取决于age> age> age 每个记录的字段是
21
。可以将其推广为
count
函数,将谓词函数作为参数。The most straightforward way would be to combine
List.length
andList.filter
.However, this is somewhat less efficient than it could be. We can do it in one pass because we don't really need to build a list of the matching people, and then iterate over that list to find its length.
List.fold_left
will let us iterate overpersonlist
, updating the initial value of0
on each iteration dependent on whether theage
field of each record is21
or not.This can be generalized as a
count
function which takes a predicate function as an argument.