Better |> ignore or return ()
So it's just a matter of curiosity.
If I want to return one, which is better?
|> ignore
or
()
There are probably other ways as well. I just want to know what is best given these:
- What is most effective
- Which is best for a production environment
- Which is most readable for long term maintenance.
source to share
I think you are comparing things that are not quite comparable here. Value ()
allows you to create a value of one, and |> ignore
is something you can use to ignore another result. These two are not exactly the same:
If you are calling a function and want to ignore the result, you can simply write:
doStuff () |> ignore
But doing the same with ()
either would have to ignore the warning:
doStuff () // warning: Result is ignored
()
... or you can assign the result to the ignore pattern _
using a binding let
:
let _ = doStuff ()
()
So, in this case it is better to use ignore
- it is built in, so it has no performance implications and it makes the code easier to read.
However, there are times when you just need to create a unit value and then ()
this is what you want (and there is no obvious way ignore
to do the same). For example:
match optMessage with
| Some message -> printfn "ANNOUNCEMENT: %s" message
| None -> ()
You can replace ()
with 42 |> ignore
to get the same result, but that would be silly!
source to share