Andry
Andry

Reputation: 16845

Dealing with null values in F#

As you can see by the mass of questions I'm asking, I'm really getting deeper and deeper into F# :)

Another doubt approaches my learning path: null values. How to handle them considering that it is necessary because of the tight integration between the .NET framework and F# (or any other language in the framework)?

To keep it simple, here's a slice of code:

let myfunc alist =
   try
      List.find (fun x -> true) alist
   with
      | :? KeyNotFoundException as ex -> (* should return null *)

How can I return a null in a function?
The null keyword is useless, unless recognized (not the same for nil).
And, generally speaking, what's the best practice when handling null returned values?

Upvotes: 0

Views: 344

Answers (1)

kvb
kvb

Reputation: 55184

I'm not quite sure what the question is. If you complete your example:

open System.Collections.Generic

let myfunc alist =
   try
      List.find (fun x -> true) alist
   with
      | :? KeyNotFoundException as ex -> null

you'll find that it compiles just fine, and the inferred type myfunc : 'a list -> 'a when 'a : null indicates that the type stored in the list that you pass in must have null as a proper value. F# is perfectly capable of dealing with null values when using types defined in C#, VB.NET, etc.

However, when you're not interoperating with code written in another .NET language, the typical approach would be to return an 'a option to indicate that a value may or may not be present. Then, your example would become:

let myfunc alist =
   try
      List.find (fun x -> true) alist
      |> Some
   with
      | :? KeyNotFoundException as ex -> None

which will work on lists containing any type (even ones which don't have null as a proper value). Of course, in this case you could just use List.tryFind (fun _ -> true) instead.

Upvotes: 6

Related Questions