type node = {
lan: string;
lat: string;
};;
let rec read_nodes_from_list list = match list with
| Xml.Element("node", _, _)::list' -> {lan="A"; lat="B"}::read_nodes_from_list list'
;;
I tried this to create a node record but it doesn't work. And suppose I have another type that has same attributes of node, how can I tell ocaml which type object to create?
Thank you.
Obviously, your function didn't work because you forgot to match with empty list:
let rec read_nodes_from_list list = match list with
| Xml.Element("node", _, _)::list' -> {lan="A"; lat="B"}::read_nodes_from_list list'
| [] -> []
What you're actually trying to do is a map operation on list, so your function could be written more elegantly as follows:
let read_nodes_from_list list =
List.map (fun (Xml.Element("node", _, _)) -> {lan="A"; lat="B"}) list
However, the function may not work because pattern matching on Xml.Element is not exhaustive. You should be careful when handling remaining cases. For example, something like this would work:
let read_nodes_from_list list =
List.map (function | (Xml.Element("node", _, _)) -> {lan="A"; lat="B"}
| _ -> {lan=""; lat=""}) list
To answer your question about record types, it considers a bad practice to have two record types with the same field label. You still can put these record types in different submodules and distinguish them using module prefixes. But as I said, having two similar record types in the same module causes confusion to you and the OCaml compiler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With