为什么函数模式匹配不起作用,而显式模式匹配却起作用?

Raw*_*ler 0 ocaml

我编写了一个函数,它接受一个数字,并返回该数字的负数版本。如果传递的数字为负数,则仅返回该数字。make_negative :: int -> int

我的第一个实现如下:

let make_negative x =
  match x with
  | 0 -> 0
  | y when y < 0 -> y
  | y when y > 0 -> -y
Run Code Online (Sandbox Code Playgroud)

当我看到这个模式时,我想我可以用以下模式替换它:

let make_negative_two =
  | 0 -> 0
  | x when x < 0 -> x
  | x when x > 0 -> -x;;
Run Code Online (Sandbox Code Playgroud)

但是,我看到以下错误:syntax error: expecting expr.

rex*_*lly 5

我对 OCaml 一点也不熟悉,事实上你的帖子是我第一次听说它,所以我的回答可能有点天真。

但是看看你的第二个解决方案,并交叉引用“学习”文档,有些东西很突出。

第二种解决方案(导致语法错误的解决方案)似乎格式错误,因为它是一个不完整的表达式。我不熟悉 OCaml 的语言术语,但以下内容确实通过了,来自我在网上找到的语法检查器。

let make_negative_two = function
  | 0 -> 0
  | x when x < 0 -> x
  | x when x > 0 -> -x;;
Run Code Online (Sandbox Code Playgroud)

如果有效的话,那就太好了!

在我看来,“function”关键字完成了表达式。


我引用了https://www2.lib.uchicago.edu/keith/ocaml-class/pattern-matching.htmlhttps://ocaml.org/problemshttps://try.ocamlpro.com来撰写此回复