Syntax OCaml文字负数?
我在学习。这是我觉得奇怪的事情:Syntax OCaml文字负数?,syntax,ocaml,Syntax,Ocaml,我在学习。这是我觉得奇怪的事情: let test_treeways x = match x with | _ when x < 0 -> -1 | _ when x > 0 -> 1 | _ -> 0;; 我将得到类型不匹配错误(因为据我所知,它将一元负号解释为部分函数应用程序,因此它将表达式的类型视为int->int。但是: test_threeways (-10);; 按预期操作(虽然这实际上是计算值,正如我所理解的,它不会将常量“减10”传递
let test_treeways x = match x with
| _ when x < 0 -> -1
| _ when x > 0 -> 1
| _ -> 0;;
我将得到类型不匹配错误(因为据我所知,它将一元负号解释为部分函数应用程序,因此它将表达式的类型视为int->int
。但是:
test_threeways (-10);;
按预期操作(虽然这实际上是计算值,正如我所理解的,它不会将常量“减10”传递给函数)
那么,如何在OCaml中写入常量负数呢?为了避免分析不准确,需要将其括起来。“test\u threeways-10”也可以表示:从test\u threeways中减去10 没有函数应用。只需重新定义一元负号,就可以看到区别:
#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 *)
#let(~-)=(+)2;;(*参见Perversives*的文档)
val(~-):int->int=
#设t=-2;;
val t:int=-2(*无函数应用,常数负数*)
#-t;;
-:int=0(*函数应用*)
您可以直接使用and~-。正如另一个答案中所暗示的那样,它们都是显式的,因此解析它们不会产生歧义。
但是,我更喜欢使用括号。只有在没有空格的情况下,源代码才会以不同的方式进行词法分析。空格只是用来分隔标记。如果不在两个字母数字标识符之间加空格,它们会形成一个更大的标识符等。样式注释:模式匹配最适合分解值。此练习应该是if构造。
#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 *)