Opinions on `+=` / `+.=`?

I’m sure this came up already but what would you think if the stdlib had a += operator (alias for incr) and +.= (for floats), and similarly for other arithmetic operators ?

Like the following?

let (+=) r x = r := !r + x
let (+.=) r x = r := !r +. x

let i = ref 0
i += 2 (* {contents = 2} *)

That would be a nice syntax, but I don’t know if you really want to do computations on integers in an imperative way, considering such a functional language. I would keep references to a limited set of use cases, for example quite complex global variables, like a global config or idk.

I think it should be there, but its not a big deal if its not, since its so easy to define it yourself.
And as much as I love functional programming, I also think OCaml should try to present itself much more as an imperative language, because not everyone wants to learn functional, and Ocaml is a very nice imperative language.
I am even thinking of writing a tutorial aimed at programming beginners, to learn programming starting with Ocaml, that would be focused on imperative stuff.

6 Likes

Like others, I think this is fine, but I’ll just note that I sometimes muse on how nice it’d be, if we could come up with the equivalent of setf/getf for ocaml. So that you could write a.(i).(j).[k] += 5

3 Likes

Be careful, or you might inspire someone to write a tutorial about OCaml as an OOP language :wink:

More seriously, I would love to see this. OCaml is functional-forward but eminently practical. I think that a tutorial focused around its imperative aspects would be incredibly valuable.

2 Likes

currently this syntax is problematic because of precedence rules; it will have to be special-cased. For example:

let (+=) r i = r := r + i

let _ =
  let x = ref 0 in
  x += 1 |> succ

this doesn’t parse as you’d expect it to.