如何重复TryParse直到F#成功?

问题描述:

对不起愚蠢的问题,但我有点困惑。
如何重复TryParse直到F#成功?

在C#中,我可以惯用做到以下几点:

int result = 0; 
while (!Int32.TryParse(someString, out result)) 
{ 
    ... 
} 

在F#我有尝试DoSomething的模式两种选择。
它要么

let (isSuccess, result) = Int32.TryParse someString 

let result = ref 0 
let isSuccess = Int32.TryParse("23", result) 

我可以做while not Int32.TryParse("23", result) do ...,但不知道是否相同与第一方案可以实现的。

P.S.当然,尾递归也是可行这里,但我感兴趣的是使用while结构。

+1

我想你已经回答了你的问题:)你可以使用第二个变体与'而'或使用递归的第一个变种... –

你可以这样做:

while (not (fst (Int32.TryParse someString))) do 
    printfn "in while loop. It's not an Int32." ; 
    someString <- Console.ReadLine(); 

或者(如果你所关心的分析结果):

while 
    let (isSuccess, result) = Int32.TryParse someString in 
    not isSuccess do 
     printfn "in while loop. It's not an Int32 ; it is %A" result; 
     someString <- Console.ReadLine(); 
+0

让内部,而...这太酷了,谢谢。 –

+0

如果你不需要,你也可以做的结果是:'Int32.TryParse“1” |> FST |> not' – mydogisbox

+0

顺便说一句,上面仍然例如需要在外部范围可变变量,如果需要的结果'while'结束后。 –