Often when learning a new technology I start with a simple console application in which the program is run in a loop it continues to prompt you for more input until you give some command like quit or exit or whatever you choose:
Enter input: someInput
someOutput
Enter input: otherInput
someoutPut
Enter input: quit
Thanks! Come again!
The code for this is in an imperative language is usually something like:
while(true) { Console.Write("\nEnter input:"); var line = Console.ReadLine(); if(line == "quit") break; doSomething(line); } Console.WriteLine("Thanks! Come Again");
While reading some F# samples, I saw some code doing essentially the same thing which looked something like:
Console.Write "\nEnter input:" let mutable input = Console.ReadLine() while input <> "quit" do if input <> "quit" then doSomething input Console.Write "\nEnter input:" input <- Console.ReadLine()
Now this just feels dirty! In a functional language explicit loop constructs like a while loop feel wrong. A different way of doing this which is more functional is to create an infinite list of actions. Where each action represents one iteration of any of the above loops. Then you just execute each action until some condition is met (like seeing the input “quit”).
let action = fun _ -> Console.Write "\nEnter input: " Console.ReadLine() let readlines = Seq.init_infinite (fun _ -> action()) let run item = if item = "quit" then Some(item) else parse item None Seq.first run readlines |> ignore Console.WriteLine "Thanks! Come Again"
This code makes use of the Seq.init_infinite which create a infinite sequence and Seq.first which enumerates the sequence until the passed in function returns Some.