'Unusual order-of-execution problem with OCaml
I'm new to OCaml. I've written this very trivial program:
open Stdio
let getline =
match In_channel.input_line In_channel.stdin with
| Some x -> x
| None -> "No input"
;;
let () =
printf "What's your name? ";
printf "Hi, %s!" getline;;
and several variations thereof.
You get the idea. I ask for the user's name and print "Hi, [name]!".
It works but the output is in the wrong order. I build the project with dune, run the executable, don't get any prompt for the name, I type it in and then I get all at once "What's your name? Hi, [name]!".
Now, I know the basics of buffering in OCaml. In fact, I remember having the same problem when dabbling in OCaml a while back. I distinctly remember reading this:
The strange order of code execution in OCaml
and I'm almost certain that adding "%!" worked. I've even tried
Out_channel.flush stdout
between the two printf's, and it doesn't work. I've tried adding a "\n" in the first printf. And I've tried this in a couple of terminals.
I'm sure it's something really trivial, possibly just basic syntax.
Solution 1:[1]
You defined getline as a variable, not a function.
A function must always accept one parameter, although that parameter can be ():
open Stdio
let getline () =
match In_channel.input_line In_channel.stdin with
| Some x -> x
| None -> "No input"
;;
let () =
printf "What's your name? ";
printf "Hi, %s!" (getline ());;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Stef |
