Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Using a custom operator as 'kvb' suggests is definitely an option. Another approach that you may find interesting in this case is to define your own 'computation expression' that automatically performs the check for <code>null</code> value at every point you specify. The code that uses it would look like this:</p> <pre><code>open System.Windows.Forms // this function returns (0) null, or (1) btn whose parent is // null or (2) button whose parent is not null let test = function | 1 -&gt; new Button(Text = "Button") | 2 -&gt; new Button(Text = "Button", Parent = new Button(Text = "Parent")) | _ -&gt; null let res = safe { let! btn = test(2) // specify number here for testing // if btn = null, this part of the computation will not execute // and the computation expression immediately returns null printfn "Text = %s" btn.Text let! parent = btn.Parent // safe access to parent printfn "Parent = %s" parent.Text // will never be null! return parent } </code></pre> <p>As you can see, when you want to use a value that can potentially be 'null', you use <code>let!</code> inside the computation expression. The computation expression can be defined so that it immediately returns <code>null</code> if the value is <code>null</code> and runs the rest of the computation otherwise. Here is the code:</p> <pre><code>type SafeNullBuilder() = member x.Return(v) = v member x.Bind(v, f) = if v = null then null else f(v) let safe = new SafeNullBuilder() </code></pre> <p>BTW: If you want to learn more about this, it is very similar to 'Maybe' monad in Haskell (or computation working with F# option type). </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload