3

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?

1 Answer 1

6

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.)

Sign up to request clarification or add additional context in comments.

2 Comments

@gasche: incr has type int ref -> unit. And it looks like the return from your function is pointless also -- it is always going to return var
Indeed, my mistake. I agree on the function return being pointless.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.