Atikae
Atikae

Reputation: 177

OCaml syntax error with let ... in

I have a quite simple issue I think, but no way to figure out what's going wrong. I want to open a file and try to failwith a custom message if the file don't exist or something else.

Here my code (sorry for 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've a syntax error on the with keyword. Someont have an idea ? Thanks.

Upvotes: 3

Views: 2265

Answers (2)

pad
pad

Reputation: 41290

The error occurred because you bound input to a value but did not return anything in the then branch.

You should do something with the value input and return () after the try/with block.

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
    ()

Upvotes: 4

Thomash
Thomash

Reputation: 6379

Your problem is that your code do nothing, you define the value «input» but don't use it and Ocaml doesn't like code that do nothing. You should write something like this :

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

Other remarks on your code:

  1. I don't think you want to use «failwith ("Impossible d'ouvrir le fichier " ^ filename)» because it raises an exception that won't be caught. You already caught it so print an error message and exit :

    (print_endline ("Impossible d'ouvrir le fichier " ^ filename); exit 1)
    
  2. You should use «begin» and «end»

Upvotes: 0

Related Questions