【问题标题】:Syntax error in "with"“with”中的语法错误
【发布时间】:2015-02-23 10:10:11
【问题描述】:

我在这段代码中有语法错误,在第二个“try”的“with”中:

let example =
    let n = (*Empty_list*) in 
        while true  do 
                try let i= function (read_line()) in 
                    try let n= execute_inst n i with (*this with*)
                        |Exception1 s -> print_endline("Exception1 "^s^)
                        |Exception2 s->  print_endline("Exception2 "^s^)
                        |Exception3 s -> print_endline("Exception3 "^s^)
                        |Exception4 -> print_endline("Exception4"); exit 0                        
                with |Exception5 -> print_endline("Exception5")
                      |Exception6 ->print_endline ("Exception6")        
        done;;

为什么会这样?

【问题讨论】:

  • 您收到的完整错误消息是什么。另外,let n = (*Empty_list*) in 无效...

标签: syntax-error ocaml let try-with


【解决方案1】:

您的代码包含太多错误,甚至几乎不像 OCaml...

  • let n = (*Empty_list*) in 这里你注释掉了表达式,结果实际上是let n = in 它不是一个有效的OCaml。

  • try let i= function (read_line()) in function 是关键字,不能这样使用

  • try let n= execute_inst n i with 这里的问题是let n= execute_inst n i 正确的语法是let <value> = <expression-1> in <expression-2>

如果您尝试修改之前绑定的值,则不会以这种方式完成。阅读参考资料。

为什么会这样?

因为,你还没有阅读 OCaml 手册。

更新

好吧,我猜你想写这样的东西

exception Exception1 of string
exception Exception2 of string
exception Exception3 of string
exception Exception4
exception Exception5
exception Exception6

let execute_inst insns insn = 
  (* do something  *)
  insns

let example f lst =
  let n = ref lst in 
  while true do 
    try let i = read_line () in 
      try n := execute_inst !n i with
      | Exception1 s -> print_endline ("Exception1 "^s)
      | Exception2 s -> print_endline ("Exception2 "^s)
      | Exception3 s -> print_endline ("Exception3 "^s)
      | Exception4   ->
        print_endline "Exception4";
        exit 0                        
    with Exception5 -> print_endline "Exception5"
         | Exception6 -> print_endline "Exception6"     
  done

这至少是一段语法正确的 OCaml 代码。这绝对不是一个应该如何在 OCaml 中编程的例子。事实上,它非常接近相反的情况。

再一次,我想建议你阅读更多关于 OCaml 的内容,这里有很多优秀的书籍,比如 Jason Hickey 写的优秀的 Introduction to OCaml,仅举一例。 ocaml.org 网站上还有很多资料可以轻轻地向您介绍 ocaml。

【讨论】:

  • 对不起那些“东西”,但这段代码是为了练习,我试图避免有人处理代码,这就是我改变一些东西的原因。现在错误只显示:“错误:语法错误”和“with”下划线
  • 问的太多了,但您能否展示导致您想要解决的错误的具体代码?上面的代码仍然有@ivg 识别的所有错误(据我所知)。
猜你喜欢
  • 2018-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多