简体   繁体   English

OCaml:如何遍历记录类型中的列表参数

[英]OCaml: How to traverse a list parameter in a record type

If I have a data structure such as如果我有这样的数据结构

type cost = int

type 'a map = {
  cities : 'a list
  routes : ('a * 'a * cost) list
}

And say I have a function with a header such as并说我有一个 function 和一个 header 例如

let nearest_cities (m : 'a map) = ...

and I want to recursively traverse the routes list, what would be the best and cleanest way of going about this?我想递归遍历路由列表,最好和最干净的方法是什么? I tried to match on the record, however I'm not sure how to recursively update the parameters of the record我试图匹配记录,但是我不确定如何递归更新记录的参数

Thanks谢谢

You say you want to update the record, but the record type as you have defined it is immutable.你说你想更新记录,但是你定义的记录类型是不可变的。 You can't change the values of the fields of such a record.您无法更改此类记录的字段值。 The usual way to handle this in a functional language is to create a new record with the desired new contents.用函数式语言处理这个问题的通常方法是创建一个包含所需新内容的新记录。

You say you want to "traverse" the list, but this isn't specific enough to offer a detailed suggestion.你说你想“遍历”列表,但这还不够具体,无法提供详细的建议。 There are functions in the List module for various kinds of traversal: List.iter , List.map , List.fold_left , and so on. List模块中有用于各种遍历的函数: List.iterList.mapList.fold_left等。

As an example, here is a function that increments all the costs of a value of type 'a map :例如,这是一个 function,它增加了类型为'a map的值的所有成本:

 let cost_incr map =
      { map with routes =
            List.map (fun (a, b, c) -> (a, b, c + 1)) map.routes
      }

(Also note you need ; after the definition of the cities field in the record type.) (另请注意,您需要在记录类型中cities字段;定义之后。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM