OCaml syntax error with let ... in

I have a pretty simple problem, I think, but I don’t understand what is going on. I want to open a file and try to crash using a special message if the file does not exist or something else.

Here is my code (sorry for the french comment):

if (argc = 1) then
    aide ()
else
    (* Si plus d'un argument, on récupère le type *)
    if argc >= 2 then
        let stage = int_of_string (Sys.argv.(1)) in
            if stage != 0 && stage != 1 then
                aide ()
            else
                ()
    else
        ()
    ;    
    (* Si plus de deux arguments, on récupère aussi l'entrée *)
    if argc >= 3 then
        let filename = Sys.argv.(2) in
        let input =
        try
            open_in filename
        with _ -> failwith ("Impossible d'ouvrir le fichier " ^ filename)
    else
        ()
    ;
;;

I have a syntax error for a keyword. Does anyone have an idea? Thank.

+3
source share
2 answers

The error occurred due to the fact that you bound inputto the value, but did not return anything to the branches then.

You must do something with the value inputand return ()after the block try/with.

if argc >= 3 then
    let filename = Sys.argv.(2) in
    let input = (* The error is in this line *)
    try
        open_in filename
    with _ -> failwith ("Impossible d'ouvrir le fichier " ^ filename)
else
    ()
+4
source

, , "input", , Ocaml , . - :

if (argc = 1) then
    aide ()
else begin
    (* Si plus d'un argument, on récupère le type *)
    if argc >= 2 then
        let stage = int_of_string (Sys.argv.(1)) in
            if stage != 0 && stage != 1 then
                aide ()
            else
                ()
    else
        ()
    ;    
    (* Si plus de deux arguments, on récupère aussi l'entrée *)
    if argc >= 3 then
        let filename = Sys.argv.(2) in
        let input =
        try
            open_in filename
        with _ -> failwith ("Impossible d'ouvrir le fichier " ^ filename)
        in
        (* Le code principal du programme qui utilise la valeur input *)
    else
        ()
    ;
end;;

:

  • , "failwith (" Impossible d'ouvrir le fichier "^ filename)", , . , :

    (print_endline ("Impossible d'ouvrir le fichier " ^ filename); exit 1)
    
  • "begin" "end"

0

All Articles