F # how to return tuple or null value

let retVal = if reader.Read() then (reader.GetString(0), getBytesData reader 1, reader.GetDateTime(2)) else null 

F # does not allow null returns

How can I return a value as a tuple or null?

+4
source share
2 answers

This does not mean that F # does not allow you to return null.

This is because then the part and the other part are of different types.

You can use the parameter type .

 let retVal = if reader.Read() then Some (reader.GetString(0), getBytesData reader 1, reader.GetDateTime(2)) else None 

when you use retVal , you use pattern matching:

 match retVal with | Some v -> ... | None -> // null case 
+11
source

To add further information to Yin Zhu's answer, the situation with a null value in F # is as follows:

  • F # types, such as tuples (e.g. int * int ), which in your case does not have null as a valid value, so you cannot use null in this case (other types of function values ​​such as int -> int , lists and most types of library F #)

  • Types from the .NET platform can be null , so you can, for example, write:

     let (rnd:Random) = null 

    This is not the idiomatic style of F #, but it is allowed.

  • If you define your own F # type, it will automatically prevent you from using null as a valid type value (which follows to minimize the use of null in F #). However, you can explicitly allow this:

     [<AllowNullLiteral>] type MyType = ... 
+8
source

Source: https://habr.com/ru/post/1311985/


All Articles