简体   繁体   中英

Syntax error in “with”

I'm having a syntax error in this code, in the "with" from the second "try":

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;;

why is it happening?

Your code contains so many errors, that it even hardly resembles OCaml...

  • let n = (*Empty_list*) in here you've commented out the expression, and the result is actually let n = in it is not a valid OCaml.

  • try let i= function (read_line()) in the function is a keyword it can't be used in a such way

  • try let n= execute_inst ni with here the problem is with let n= execute_inst ni the correct syntax is let <value> = <expression-1> in <expression-2>

If you're trying to modify the previously bound value, then it is not done in this way. Read about references.

why is it happening?

Because, you haven't read OCaml manual.

Update

Ok, I can guess, that you were trying to write something like this

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

This is at least a piece of syntactically correct OCaml code. This is absolutely not an example of how one should program in OCaml. Indeed, it is quite near to the opposite.

Yet again, I would like to suggest you to read more about OCaml, there're excellent books, like an excellent Introduction to OCaml written by Jason Hickey, just to mention one. There're also lots of materials the can gently introduce you to ocaml on the ocaml.org site.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM