Functional programming 关于OCaml模式匹配语法
我正在学习OCaml教程 他们提供了以下两个功能,并表示它们是等效的Functional programming 关于OCaml模式匹配语法,functional-programming,ocaml,Functional Programming,Ocaml,我正在学习OCaml教程 他们提供了以下两个功能,并表示它们是等效的 let string_of_int x = match x with | 0 -> "zero" | 1 -> "one" | 2 -> "two" | _ -> "many" let string_of_int2 = function | 0 -> "zero" | 1 -> "one" | 2 -> "two" | _ -&
let string_of_int x = match x with
| 0 -> "zero"
| 1 -> "one"
| 2 -> "two"
| _ -> "many"
let string_of_int2 = function
| 0 -> "zero"
| 1 -> "one"
| 2 -> "two"
| _ -> "many"
我的问题是关于上述函数的语法
|0->
,而是简单地编写了0->
,并且函数仍然以相同的方式工作。教程在函数中添加了额外的|
有什么特殊原因吗函数
关键字的用途是什么?为什么第一个函数中没有这个关键字
function
语法是一个缩写:function[CASES]
与fun x->match x with[CASES]
相同。有一个细微的区别,就是函数
不可能用参数名来隐藏另一个变量
let string\u of_int x=[EXP]
本身就是let string\u of_int=fun x->[EXP]
的缩写
因此,近似地说,“规范”语法使用fun
和match
,其他一切都是糖。如果将这两个扩展应用于函数的两个版本,您将看到相同的代码结果(当然是模阿尔法等价:)