Take the 2-minute tour ×

I'm learning. This is something I found strange:

let test_treeways x = match x with
  | _ when x < 0 -> -1
  | _ when x > 0 -> 1
  | _ -> 0;;

If I then call it like this:

test_threeways -10;;

I will get type mismatch error (because, as far as I understand, it interprets unary minus as if it was partial function application, so it considers the type of the expression to be int -> int. However, this:

test_threeways (-10);;

acts as expected (though this actually calculates the value, as I could understand, it doesn't pass a constant "minus ten" to the function.

So, how do you write constant negative numbers in OCaml?

share|improve this question
add comment

2 Answers

up vote 6 down vote accepted

You need to enclose it in order to avoid parsing amiguity. "test_threeways -10" could also mean: substract 10 from test_threeways.

And there is no function application involved. Just redefine the unary minus, to see the difference:

#let (~-) = (+) 2 ;; (* See documentation of pervarsives *)
val ( ~- ) : int -> int = <fun>
# let t = -2 ;; 
val t : int = -2 (* no function application, constant negative number *)
# -t ;;
- : int = 0   (* function application *)
share|improve this answer
Only if without the space the source would be lexed in a different way. Whitespace is just to delimit tokens. If you don't put whitespace between two alphanumeric identifiers they form a single bigger one etc. –  lukstafi Apr 18 '13 at 16:15
add comment

You can use ~- and ~-. directly (as hinted in the other answer), they are both explicitly prefix operators so parsing them is not ambiguous. However I prefer using parentheses.

share|improve this answer
add comment

Your Answer

