Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write this C# code in F#

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!

like image 414
Gerardo Contijoch Avatar asked Apr 08 '13 14:04

Gerardo Contijoch


2 Answers

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 *)
like image 173
pad Avatar answered Oct 08 '22 11:10

pad


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
like image 43
Daniel Avatar answered Oct 08 '22 12:10

Daniel