Snippets

Cameron Presley F# Input Validation

Updated by Former user

File snippet.fs Modified

  • Ignore whitespace
  • Hide word diff
         | Some x -> x
         | None -> promptUser inputMethod message matchingExpression
         
-// Example Usages
+// Example Reading String input
 
 let sentenceMatchingExpression (input:string) =
     if input.StartsWith "A" then Some input
 
 printfn "You entered %s" result
 
-
+// Example reading input that needs to be coereced back into a primitive
 let validNumberOfHoursToWork (input:string) =
     match System.Int32.TryParse(input) with
         | (true,int) -> if int <= 40 && int >= 1 then Some input
Created by Former user

File snippet.fs Added

  • Ignore whitespace
  • Hide word diff
+ let getKeyBoardInput () =
+    System.Console.ReadLine()
+
+let rec promptUser (inputMethod:unit->string) (message:string) (matchingExpression:string->string option) =
+    let formattedMessage = Printf.TextWriterFormat<unit>(message)
+    printfn formattedMessage
+    let input = inputMethod()
+       
+    let result = matchingExpression input
+    match result with
+        | Some x -> x
+        | None -> promptUser inputMethod message matchingExpression
+        
+// Example Usages
+
+let sentenceMatchingExpression (input:string) =
+    if input.StartsWith "A" then Some input
+    else None
+    
+let prompt = "Please enter a string that starts with A."
+
+let result = promptUser getKeyboardInput prompt sentenceMatchingExpression
+
+printfn "You entered %s" result
+
+
+let validNumberOfHoursToWork (input:string) =
+    match System.Int32.TryParse(input) with
+        | (true,int) -> if int <= 40 && int >= 1 then Some input
+                        else None
+        | _ -> None
+        
+let numHoursWorkedPrompt = "Please enter then number of hours worked."
+
+let numHoursWorked = (promptUser getKeyBoardInput numHoursWorkedPrompt validNumberOfHoursToWork) |> Int32.Parse
+
+printfn "You worked %i" numHoursWorked
HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.