ocaml - 为什么 `;;` 在 utop 中给我一个语法错误?

标签 ocaml utop

我正在开发一个简短的项目,将小程序从 python 转换为 java,反之亦然。 我创建了以下代码,并在 utop 中对其进行了测试。

let c = 
let x = "for (int i = 0; i<10; i++)" 
and y = "for i in range(0,10):"
in function
| x -> y
| y -> x
| _ -> "Oh no!!";;

出于某种原因,x 和 y 都被认为是未绑定(bind)的,但同时任何参数似乎都与 x 匹配。

需要按照什么顺序编写所有内容才能使其正常工作?

最佳答案

只是跟进您的答案。

In pattern-matching, matching to a variable doesn't necessarily seem to match to its value.

这就是为什么它被称为模式匹配而不是值匹配的原因。

顾名思义,模式匹配用于根据模式而不是来匹配事物。在问题中显示的代码中,您实际上并未将任何内容与 xy 进行比较,您正在定义名为 x 的模式>y 可以匹配任何内容。请参阅下面的示例:

match 2 with
| x -> "Hey, I matched!"
| _ -> "Oh, I didn't match.";;

- : string = "Hey, I matched!"

Note that this works even if x was previously defined. In the match case, the x from the pattern is actually shadowing the other one.

let x = 42 in
match 1337 with
| x -> Printf.printf "Matched %d\n!" x
| _ -> ();;

Matched 1337!
- : unit = ()

另一方面,模式 i 当 i = x 实际上与外部变量 x 的值匹配,这就是为什么你的 self-答案有效。但这无论如何都不是模式的用途。

您实际上想要做的不是模式匹配,它是一个简单的条件语句。

let c argument = 
  let x = "for (int i = 0; i<10; i++)"  in
  let y = "for i in range(0,10):" in
  if argument = x then y
  else if argument = y then x
  else "Oh no!";;

val c : string -> string = <fun>

它正在发挥作用:

c "for (int i = 0; i<10; i++)";;
- : string = "for i in range(0,10):"

c "for i in range(0,10):";;
- : string = "for (int i = 0; i<10; i++)"

c "whatever";;
- : string = "Oh no!"

此外,除非您定义相互递归值,否则不要使用 and

关于ocaml - 为什么 `;;` 在 utop 中给我一个语法错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47612574/

相关文章:

module - 如何在 utop 中加载 .ml 文件及其对应的 .mli 文件?

generics - 为什么编译器会将两个具有不同名称的等效签名的泛型类型变量识别为不同类型?

functional-programming - 是否可以在 Ocaml 中实现罗素悖论?

function - 函数中的 OCaml 语法错误

Ocaml 改变类型 'a tree to ' b 树

ocaml - 使用 ocaml 和 jane street async 的可变数据

ocaml - ocaml utop 中的 show_module 乏味

ocaml - OCaml中的 "int/2"类型是什么

ocaml - 有没有办法在 utop 中列出模块的所有功能?

emacs - Merlin 提示同一个项目中缺少一个模块