A usual pattern for CLI application is to run in infinite loop, until user types some quit command. Like, in C language:
while(1){
scanf("%c", &op);
...
else if(op == "q")
break;
}
What would be the pattern for such console application in F# (tried to use tail recursrion, but failed)?
To make an infinite loop, just use true as your condition. true is always true, so the loop will repeat forever.
An infinite loop occurs when a condition always evaluates to true. Usually, this is an error. For example, you might have a loop that decrements until it reaches 0.
An infinite loop (sometimes called an endless loop ) is a piece of coding that lacks a functional exit so that it repeats indefinitely. In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.
What is while(1)? The while(1) acts as an infinite loop that runs continually until a break statement is explicitly issued.
Typing in browser, thus may contain errors:
let rec main() =
let c = System.Console.ReadKey()
if c.Key = System.ConsoleKey.Q then () // TODO: cleanup and exit
else
// TODO: do something in main
main()
Here's a none blocking version that responds to single key press.
open System
let rec main() =
// run code here
// you may want to sleep to prevent 100% CPU usage
// Threading.Thread.Sleep(1);
if Console.KeyAvailable then
match Console.ReadKey().Key with
| ConsoleKey.Q -> ()
| _ -> main()
else
main()
main()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With