OCaml literal negative number?

不羁的心 提交于 2019-12-22 06:33:18

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/16041393/ocaml-literal-negative-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!