Can I generalize field updates in OCaml?

I am a very novice OCaml programmer, so please forgive me if this is a stupid / obvious question. There is a lot to learn, and I may have missed it in the documentation.

I have a base code that starts to look like this:

let update_x p x =
  add_delta p;
  p.x <- x;
  refresh p

let update_y p y =
  add_delta p;
  p.y <- y;
  refresh p

let update_z p z =
  add_delta p;
  p.z <- z;
  refresh p 

Duplicate starts to beat me because I want to write something like this:

let update_scalar p scalar value =
    add_delta p;
    magic_reflection (p, scalar) <- value;
    refresh p

That way, when I update x, I can simply call:

update_scalar p 'x' value

This causes "macros!". for me, but I don’t think OCaml has a macro system. What else can I do?

+3
source share
3 answers

, , , OCaml. camlp4 ( , , , , )

UPDATE_FIELD x f y

x.f <- y

- .

. camlp4, OCaml 3.10 , . . OCaml.

+1

, , :

let update_gen set p x =
  add_delta p;
  set p x;
  refresh p

let update_x = update_gen (fun p v -> p.x <- v)
let update_y = update_gen (fun p v -> p.y <- v)
let update_z = update_gen (fun p v -> p.z <- v)

OCaml (camlp4), .

+5

, ocaml . :

open Printf

type t = { mutable x : float; mutable y : float; mutable z : float; mutable t : int; }

let add_delta p = p.t <- p.t + 1
let refresh p = printf "%d) %.2f %.2f %.2f\n" p.t p.x p.y p.z

DEFINE UPD(x) = fun p v ->
  add_delta p;
  p.x <- v;
  refresh p

let update_x = UPD(x)
let update_y = UPD(y)
let update_z = UPD(z)

let () =
  let p = { x = 0.; y = 0.; z = 0.; t = 0; } in
  update_x p 0.1;
  update_y p 0.3;
  update_z p 2.0

:

ocamlfind ocamlc -package camlp4.macro -syntax camlp4o q.ml -o q

:

camlp4o Camlp4MacroParser.cmo q.ml
0

Source: https://habr.com/ru/post/1698444/


All Articles