为什么`;;`在utop中给我一个语法错误? [英] Why is `;;` giving me a syntax error in utop?

查看:77
本文介绍了为什么`;;`在utop中给我一个语法错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working on a short project to convert small programs from python to java and visa versa. I created the following code, and tested it in 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都被认为是未绑定的,但同时任何参数似乎都与x匹配.

For some reason, x & y are both considered unbound, yet at the same time any parameter seems to match to x.

一切都需要以什么顺序写才能完成这项工作?

What order does everything need to be written in to make this work?

推荐答案

只需跟进您的答案即可.

Simply to follow up with your answer.

在模式匹配中,与变量的匹配不一定与它的值匹配.

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

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

This is the very reason why it's called pattern-matching and not value-matching.

顾名思义, pattern-matching 用于将事物与 patterns 而不是 values 进行匹配.在问题中显示的代码中,实际上并没有将任何内容与xy进行比较,而是定义了名为xy的模式,该模式可以匹配任何内容.请参见下面的示例:

As the name implies, pattern-matching is used to match things against patterns, not values. In the code you show in the question, you are not actually comparing anything to x or y, you are defining patterns named x and y that can match anything. See the example below:

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

- : string = "Hey, I matched!"

请注意,即使先前定义了x,此方法也有效.在比赛中 在这种情况下,模式中的x实际上是另一个的 shadowing .

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 when i = x实际上与外部变量x的值匹配,这就是为什么您的自我回答中的代码起作用的原因.但这毕竟不是模式.

On the other hand, the pattern i when i = x is actually matching against the value of the outer variable x, which is why the code in your self-answer works. But this is not what patterns are for anyway.

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

What you're actually trying to do is not a pattern-matching, it is a simple conditional statement.

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.

这篇关于为什么`;;`在utop中给我一个语法错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆