Tuesday 27 September 2011

Null coalescing operator in F#

I'm converting some C# code into F# and I was wondering where the lovely ?? operator from C# had gone. In C# we have ?? as a binary infix operator meaning

if left is null then right else left

My first crack at (re-)implementing this in F# gave me compiler headaches and so a quick trawl on the web revealed that F# interprets operators starting with (or containing, not sure at the moment) a question mark as unary operators. Aha! That would explain it. So then I defined

let inline (/??) x y = if x = null then y else x

and it seemed to work. That is, it seemed to work until I tried values slightly more complex than strings for x and y.

let y () = printfn "test" ; 2 ;;

Ho hum! Now evaluating the new operator reveals a subtlety. F# evaluates both parameters, which is unlike the if .. then .. else implementation.


"334" /?? y();;
test
val it : string = "334"


Hmmm. How should this be handled? Clearly the parameters could be wrapped in lambda functions but I'm not sure about that.... More thought required. Call back later to check.

P.S. I found another implementation, but it shares the same issue (although there are other interesting operators provided as well) unfortunately