Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F#: printf vs Console.WriteLine

I am playing around in the f# interactive window and discovered that printf did not work as I expected. In the following snippet, the ReadLine executes before the first printf

let run () = 
    printf "What is your name?" 
    Console.Out.Flush()
    let value = System.Console.ReadLine()
    printf "Hello, %s, nice to meet you!" value

run()

If I change the printf to Console.WriteLine it works as expected.

let run () = 
    Console.Out.WriteLine "What is your name?"
    Console.Out.Flush()
    let value = System.Console.ReadLine()
    printf "Hello, %s, nice to meet you!" value

run()

What is going on with printf? Is there a flush call I can get it to print prior to readline? Is there an f# readline that I should be using?

----------------- [Edit] --------------------

After reading Fyodor Soikin's answer, I tried the following to verify. Sure enough, What was printed to the screen was Hello and after I entered some input, it printed World.

open System
let run () = 
    printf "Hello\n World"
    let value = System.Console.ReadLine()
    let msg = sprintf "Hello, %s, nice to meet you!" value
    printf "%s" msg
run()
like image 510
Phillip Scott Givens Avatar asked Jun 12 '16 17:06

Phillip Scott Givens


1 Answers

printf is equivalent to Console.Write, and printfn is equivalent to Console.WriteLine. You're comparing functions that are not equivalent.

Just replace your printf with printfn, and your example will work as expected.


Why does it not work with printf and Console.Write

This is simply the way FSI functions: it doesn't print text to the output window until your program produces a newline. There is a somewhat good motivation for it: if FSI printed out text right away, it might break your output with its own output of some intermediate information.

Calling Console.Flush has nothing to do with it. When your program runs in FSI, you don't actually have direct access to console, it goes through FSI's own filter. FSI does receive your input right away (i.e. there is no need to call Flush), it just doesn't print it out right away (see above).

If you run your program by itself, not in FSI, then your output will be rendered as you expect.

like image 66
Fyodor Soikin Avatar answered Sep 28 '22 01:09

Fyodor Soikin