我正在开发一个简短的项目,将小程序从 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.
这就是为什么它被称为模式匹配而不是值匹配的原因。
顾名思义,模式匹配用于根据模式而不是值来匹配事物。在问题中显示的代码中,您实际上并未将任何内容与 x
或 y
进行比较,您正在定义名为 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, thex
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/