如何用OCAML中的特定属性计数列表的记录?

发布于 2025-02-04 01:48:13 字数 332 浏览 3 评论 0原文

可以说,我们有一个记录,该记录定义了具有属性名称>和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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

林空鹿饮溪 2025-02-11 01:48:13

最直接的方法是组合list.lengthlist.filter

List.(personlist |> filter (fun p -> p.age = 21) |> length)

但是,这效率不如可能。我们可以在一次通过中做到这一点,因为我们实际上不需要构建匹配的人的列表,然后迭代该列表以找到其长度。

list.fold_left将让我们通过personList进行迭代,在每次迭代中更新0的初始值,取决于age> age> age 每个记录的字段是21

List.fold_left (fun i {age; _} -> i + if age = 21 then 1 else 0) 0 personlist

可以将其推广为count函数,将谓词函数作为参数。

let count p lst = 
  lst 
  |> List.fold_left (fun i x -> i + Bool.to_int (p x)) 0

The most straightforward way would be to combine List.length and List.filter.

List.(personlist |> filter (fun p -> p.age = 21) |> length)

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 over personlist, updating the initial value of 0 on each iteration dependent on whether the age field of each record is 21 or not.

List.fold_left (fun i {age; _} -> i + if age = 21 then 1 else 0) 0 personlist

This can be generalized as a count function which takes a predicate function as an argument.

let count p lst = 
  lst 
  |> List.fold_left (fun i x -> i + Bool.to_int (p x)) 0
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文