我正在努力解决如何在F#中完成以下任务的问题。以下是我要复制的简化的C#伪代码等效项。
var x = await GetXAsync();
if (x == null) return "not found";
var y = await GetYAsync(x);
return y;
我最初的F#版本看起来像:
task {
let! x = GetXAsync()
match x with
| None -> // need to return a hard-coded value here
| Some x` ->
let! y = GetYAsync(x`)
// More code
// return some value based on y here
}
显然这很糟糕,但是我不确定如何进行。我应该在这里尝试完整的ROP风格的编程,还是有一些更简单的方法?
在您的示例中,您正在返回"not found"
字符串,以表明某个函数出了问题,否则该函数返回了字符串。我不会这样做,因为很难区分一切正常的情况和无效的情况。
如果GetXAsync
返回的事实null
表明失败,那么我将使用异常。F#async对传播这些内容提供了很好的支持,您可以使用捕获它们try .. with
。在F#中使用异常来处理特殊情况并没有错!
exception InvalidX of string
let GetXAsync() = async {
// whetever code that calculates 'failed' and 'result' goes here
if failed then raise (InvalidX "not found")
return result }
然后,您可以调用函数,并且异常会自动传播。
async {
let! x = GetXAsync()
let! y = GetYAsync(x)
return y }
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句