Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite main loop in F#

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)?

like image 422
Arnthor Avatar asked Apr 16 '12 17:04

Arnthor


People also ask

How do you do an infinite loop?

To make an infinite loop, just use true as your condition. true is always true, so the loop will repeat forever.

What's an infinite loop example?

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.

What is an infinite loop in?

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.

Is while 1 an infinite loop?

What is while(1)? The while(1) acts as an infinite loop that runs continually until a break statement is explicitly issued.


2 Answers

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()
like image 61
desco Avatar answered Sep 21 '22 16:09

desco


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()
like image 36
gradbot Avatar answered Sep 21 '22 16:09

gradbot