OCaml文字负数吗? [英] OCaml literal negative number?

查看:79
本文介绍了OCaml文字负数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习.我发现这很奇怪:

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;;

如果我再这样称呼它:

test_threeways -10;;

我将收到类型不匹配错误(因为据我所知,它将一元减号解释为部分函数应用程序,因此它认为表达式的类型为int -> int.但是,这:

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.

那么,如何在OCaml中写入恒定的负数?

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

推荐答案

您需要将其围起来以避免解析歧义. "test_threeways -10"也可能意味着:从test_threeways中减去10.

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

这篇关于OCaml文字负数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆