Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better to |> ignore or return ()

Tags:

f#

So this is just a curiosity question.

If I want to return unit, which is better practice?

|> ignore

or

()

There's probably other ways as well. I just want to know what's best, considering these:

  • What is most performant
  • What is best practice for a production environment
  • What is most readable for long term maintanance
like image 811
Anthony Russell Avatar asked Jun 06 '17 15:06

Anthony Russell


2 Answers

I think you are comparing things that are not quite comparable here. The () value lets you create the unit value, while |> ignore is what you can use to ignore some other result. The two are not exactly the same:

If you are calling a function and you want to ignore the result, you can write just:

doStuff () |> ignore

But doing the same with () would require you to either ignore the warning:

doStuff () // warning: Result is ignored
()

... or you could assign the result to an ignore pattern _ using let binding:

let _ = doStuff ()
()

So, in this case, using ignore is better - it is inlined, so it has no performance implications and it leads to code that is easier to read.

That said, there are cases where you just need to create a unit value and then () is what you need (and there is no obvious way ignore would let you do the same). For example:

match optMessage with
| Some message -> printfn "ANNOUNCEMENT: %s" message
| None -> ()

You could replace () with 42 |> ignore to get the same result, but it would be silly!

like image 169
Tomas Petricek Avatar answered Oct 13 '22 05:10

Tomas Petricek


ignore is an inlined function so both will produce exactly the same IL.

ignore is more explicit and therefore more readable, and that's why it exists, so you should probably prefer that.

like image 20
Tim Rogers Avatar answered Oct 13 '22 06:10

Tim Rogers