Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml: creating a record from a function

Tags:

ocaml

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.

like image 392
Steve Avatar asked Jan 22 '26 01:01

Steve


1 Answers

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.

like image 184
pad Avatar answered Jan 25 '26 17:01

pad