Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ocaml: How to "easy" map a list of records to a list of record.field?

Tags:

record

ocaml

Suppose that I have the following record:

type t = {a:int}

In order to select the values of field a from a list I do the following:

let x = [{a=1};{a=2}]
let y = List.map (fun t -> t.a) x

This is a bit "unclean" to me. As a comparison, In Haskell I would do the following:

data T = T { a :: Int}  
x = [T {a = 1}, T {a = 2}]
y = map a x

Is there a way to write something similar in Ocaml (maybe using external libraries)? If not possible can someone explain why this limitation?

like image 803
Calin Avatar asked May 14 '11 18:05

Calin


2 Answers

If you use Jane Street's fieldslib library, available with core, then you can write:

type t = { a:int; b:int } with fields

and that gives you a and b as selector functions of type t -> int

It also gives you a submodule called Fields of so-called first-class fields, which include the selector, the mutator, and, critically for some applications, the string name of the field. This is very useful for generating good error messages in validations functions, for example.

You also get some higher-order functions on the entire record, most usefully a fold over the record.

like image 94
yzzlr Avatar answered Sep 28 '22 02:09

yzzlr


Unlike Standard ML, Ocaml doesn't have first-class selectors for records.(source)

As for why it cannot be done, that's simply a design choice that was made.

like image 41
Sebastian Paaske Tørholm Avatar answered Sep 28 '22 02:09

Sebastian Paaske Tørholm