Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read user input using f# interactive in visual studio?

So I am trying to do something simple:

 printfn "Enter a number:"
    try
       let x = System.Console.ReadLine();
       Some(int32(x))
    with
       | :? System.FormatException -> printfn "Invalid number!"
                                      Some(0)

I want to print the message, then get the user to input a number, and try to convert it to an int and return it.

If I just compile the code (by typing fsc a3.fs on the command line), it works fine. It pauses, waits for input, then returns Some(int).

If I copy and paste the code into the FSI on the command line, it works great.

But when I am in visual studio, and I run the code in the FSI (highlight + alt+enter), it just goes right over the input part and the exception is thrown (and caught).

Here is the output when I run in the FSI (in visual studio):

Enter a number:
Invalid number!
0

As you can see, It doesnt ever actually pause and wait for me to enter input.

Anyone know how to make this work?

Thanks!

like image 254
Toadums Avatar asked Nov 05 '11 19:11

Toadums


2 Answers

The F# Interactive console in Visual Studio does not support reading input, so there is no way to ask for an input from the console. If you're running code interactively, you can always enter the input in the editor, so the best workaround is to have let binding at the beginning where you enter the input before running your code. You can use #if to support both scenarios:

#if INTERACTIVE
// TODO: Enter input here when running in F# Interactive
let input = "42"
#endif

try 
    #if INTERACTIVE
    Some(int32 input)
    #else
    let x = System.Console.ReadLine(); 
    Some(int32(x)) 
    #endif
with 
    | :? System.FormatException -> 
        printfn "Invalid number!" 
        Some(0) 
like image 168
Tomas Petricek Avatar answered Sep 21 '22 16:09

Tomas Petricek


If you open F# interactive as its own process (by directly running fsi.exe, the code works fine - here is what happened to me:

> printfn "Enter a number:"
- let r =
-     try
-        let x = System.Console.ReadLine();
-        Some(int32(x))
-     with
-        | :? System.FormatException -> printfn "Invalid number!"
-                                       Some(0)
- ;;
Enter a number:
5

val r : int32 option = Some 5
like image 31
John Palmer Avatar answered Sep 19 '22 16:09

John Palmer