I'm used to write code like this in C#:
SomeObj obj;
try{
// this may throw SomeException
obj = GetSomeObj();
}catch(SomeException){
// Log error...
obj = GetSomeDefaultValue();
}
obj.DoSomething();
This is the way I translated it in F# (obj being a list):
let mutable obj = []
try
obj <- getSomeObj
with
| ex ->
// Log ex
obj <- getSomeDefaultValue
doSomething obj
Is there any way to do this in F# without using a mutable variable? Is there a more 'elegant' way to handle this situation in F#?
Thank you!
The F#-ish way is to return the same type of expression in both branches:
let obj =
try
getSomeObj()
with
| ex ->
// Log ex
getSomeDefaultValue()
doSomething obj
In F#, you can handle exceptions using option
type. This is an advantage when there is no obvious default value, and the compiler forces you to handle exceptional cases.
let objOpt =
try
Some(getSomeObj())
with
| ex ->
// Log ex
None
match objOpt with
| Some obj -> doSomething obj
| None -> (* Do something else *)
Wrapping this logic in functions...
let attempt f = try Some(f()) with _ -> None
let orElse f = function None -> f() | Some x -> x
...it could be:
attempt getSomeObj |> orElse getSomeDefaultValue
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With