简体   繁体   中英

How to print specific index a list of lists in OCaml?

How can i print a specific index of a list and, of a list of lists?

[["Anne";"Brazil";"42";"\n"];
 ["Bernard";"France";"34";"\n"];
 ["Charlie";"USA";"65";"\n"]]

Example: If i want to print "Brazil" how can i access it's index?

Thank you!

Cheers!

Your question isn't very clear. Here are some observations.

Thinking of OCaml lists in terms of indices is not a good approach. OCaml lists really are lists--accessed in one direction only, with linear time to access any one element. They aren't actually arrays--with constant time access to any element. Some other languages treat these structures as if they were the same, but they aren't.

What you seem to be saying is that you are starting with a known name like "Brazil", and you want to access the list element with that name. Putting this more generally, you want to access an element of a list with certain properties.

One standard function for this general problem is List.find . You give it a boolean function for the desired property and a list. It returns the element or raises an exception if there's no such element.

You could find elements by last name something like this:

let has_las_name n l =
    match l with
    | _ :: lname :: _ -> lname = n
    | _ -> false

let brazil_element = List.find (has_last_name "Brazil") mylist

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