I am trying to write a function to increment a mutable int
by a specified amount.
let increase var:int ref amount = (var := !var+amount;var);;
This is what I came up with, but it produces errors. What is the correct way to do it?
Your only problem is in the specification of the type of var
. You need to use parentheses:
# let increase (var: int ref) amount = var := !var + amount; var;;
val increase : int ref -> int -> int ref = <fun>
For what it's worth, the type specification is optional. OCaml will infer the type.
(I would personally consider having the function return unit
, which would make it analogous to the built-in function incr
.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.