shamp7598
shamp7598

Reputation: 39

Why can I not print this input a second time in OCaml?

I am very new to OCaml and am attempting to learn and write a program at the same time. I am writing a palindrome program. I am attempting to get a string from the user such as d e v e d or Hello World! or loud all of the preceding are valid user input. I need to read these strings and display them then reverse them and check if it is a palindrome or not. I did the following code...

print_string "Enter a string: ";
let str = read_line () in
Printf.printf "%s\n" str;;

Printf.printf "%s\n" str;;

this works fine and will give the print, Enter a string: d e v e d or Enter a string: Hello World! The issue comes when I try to add another Printf.printf "%s\n" str;; into the code. it gives me an error of File "main.ml", line 5, characters 21-24: Error: Unbound value str with line 5 being the line of the 2nd Printf.printf statement. I have tried this with no ; for both of the print statements, with 1 or with 2 and I get the same error each time. Does anyone with more OCaml knowledge know why I get this error.

Upvotes: 0

Views: 122

Answers (2)

Chris
Chris

Reputation: 36680

A well-formed OCaml program has no need for ;; tokens. The key is not to use more of these, but fewer, with only top-level bindings/definitions.

E.g.

let () = 
  print_string "Enter a string: ";
  let str = read_line () in
  Printf.printf "%s\n" str;
  Printf.printf "%s\n" str

The above has a local binding which parses the same as:

let () = 
  print_string "Enter a string: ";
  let str = read_line () in
  (Printf.printf "%s\n" str;
   Printf.printf "%s\n" str)

Upvotes: 0

J D
J D

Reputation: 48707

Because of your use of in your code parses as:

(let str = read_line () in Printf.printf "%s\n" str);;

and then a completely separate:

Printf.printf "%s\n" str;;

So str is local to the first printf.

You want:

let str = read_line ();;
Printf.printf "%s\n" str;;
Printf.printf "%s\n" str;;

which is three separate definitions. The first defines a global variable str.

Upvotes: 2

Related Questions