我从F#开始,我不明白什么是构造值初始化的最佳方法:
let x = TryCalculateX() // for example, searching in DB
if x = null then
// for example, we create it ourself and out it into DB
let x = TryAnotherCalcultaion()
someProcessing x // x is now initialized => Ok
someProcessing x // here I use old, not initialized x! => Fails
您如何处理类似情况?
更新。我设计的最好的是:
let getX() =
let res = TryCalculateX()
if res = null then
let res = TryAnotherCalcultaion()
res
else
res
真的不是很酷,恕我直言
更新2. @ChaosPandion建议很好的解决方法:
let x =
match TryCalculateX() with
| null -> TryAnotherCalculation()
| x -> x
someProcessing x
但是,如果再增加一层嵌套,这也就不是很好了:
let x =
match TryCalculateX() with
| null ->
match TryAnotherCalculation() with
| null -> OneMoreCalculation()
| y -> y
| x -> x
someProcessing x
也许还有一些更通用的模式可以应用?
更新3.再次感谢@ChaosPandion,这是一个通用的解决方案:
// Different initialization strategies
let x() = printfn("x"); None
let y() = printfn("y"); None
let z() = printfn("z"); Some(1)
// Sequence of strategies
let a = seq {
yield x()
yield y()
yield z()
}
// Initializing function
let init what = Seq.find (fun el -> Option.isSome el) what
// Initializing
let b = init a
F#交互式打印:
xyz ... val b:int选项=大约1
以下是一个很好的约定。它可以使用,null
但我建议您返回一个'a option
类型。
选项
let x =
match TryCalculateX() with
| Some x -> x
| None -> TryAnotherCalculation()
someProcessing x
空值
let x =
match TryCalculateX() with
| null -> TryAnotherCalculation()
| x -> x
someProcessing x
顺序
假设您编写了每次返回的尝试,option
那么您可以编写一系列优美的尝试。
let x = seq {
yield firstTry ()
yield secondTry ()
yield thirdTry ()
yield sensibleDefault
} |> Seq.pick id
someProcessing x
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句