Snippets

Cameron Presley F# Input Validation

Created by Cameron Presley last modified by unrecognized user
 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 Reading String input

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

// 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
                        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

Comments (0)