Panagiotis Grontas
Panagiotis Grontas

Reputation: 143

FSharp Options And Null

I am having trouble with the following F sharp function:

let compare (a:int option list) (b:int option list) =         
let r =
    if a.Tail = [None] && b.Tail = [None] then 
        [None]
    elif a.Tail = [None] then
        [b.Head;None]
    elif b.Tail = [None] then
        [a.Head; None]
    else
        if a=b then
            a
        else
           [None]
r

When I run it with the following arguments

compare [Some 1] [Some 0]

the answer is

[null] 

instead of

[None]

Can somebody explain why; Thank you!

Upvotes: 1

Views: 868

Answers (2)

pad
pad

Reputation: 41290

Actually, your compare function gives the right answer. The fsi printer prints None as null, which is a little misleading.

You can test that None is incompatible to unsafe null values as follows:

let xs = compare [Some 1] [Some 0]
let ys = [None]
let zs = [null]
let test1 = xs = ys;; // true
let test2 = xs = zs;; // error: The type 'int option' does not have 'null' as a proper value

BTW, your function has wrong indentation and is difficult to read. You can improve its readability using pattern-matching:

let compare (a:int option list) b =         
 let r =
    match a, b with
    | [_; None], [_; None] -> [None]
    | [_; None], y::_ -> [y; None]
    | x::_, [_; None] -> [x; None]
    | _ when a = b -> a
    | _ -> [None]
 r

Upvotes: 1

Gus
Gus

Reputation: 26174

Is the way it is displayed but in fact the value is None. If you try this

Option.isNone  ( ( compare [Some 1] [Some 0] ).[0] ) ;;

You get

val it : bool = true

Upvotes: 2

Related Questions