简体   繁体   中英

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

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.

As an example, here is a function that increments all the costs of a value of type '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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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