loop/recurse直到输入有效

loop/recurse until input is valid

我正在尝试编写一些代码来不断询问用户,直到输入有效的文件路径或 "exit"。

我现在拥有的:

let (|ValidPath|_|) str =
    if File.Exists str then Some ValidPath
    else None

type Return =
    |Path of string
    |Exit

let rec ask =
    printfn "%s" "Please enter a valid path or \"exit\""
    let input = Console.ReadLine()
    match input with
    | "exit" -> Exit
    | ValidPath -> Path input
    | _ -> ask

ask 函数有一个 The value 'aks' will be evaluated as part of its own definition 错误。

我能做什么?

问题是 ask 不是一个函数,它是一个递归值。你需要带一个参数才能使它成为一个函数:

let rec ask () =
    printfn "%s" "Please enter a valid path or \"exit\""
    let input = Console.ReadLine()
    match input with
    | "exit" -> Exit
    | ValidPath -> Path input
    | _ -> ask ()