Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It might worth adding that this is not just a property of <code>if</code>. F# is an expression-based language meaning that pretty much every piece of code (aside from type declarations and a few exceptions) is an <em>expression</em> that evaluates to some result. In fact, F# does not call <code>if</code> the if <em>statement</em>, but an if <em>expression</em>.</p> <p>This means that you can use <code>if</code> in unexpected places. For example, this might be useful:</p> <pre><code>x/2 + (if x%2=0 then 0 else 1) </code></pre> <p>As already explained by Garry, if you omit <code>else</code>, then the expression still needs to return something - if the result was to be an <code>int</code>, then it would not really make sense (which number should the compiler pick?), so it requires that the result is of type <code>unit</code>, which is a special type representing "no result".</p> <p>The <code>unit</code> type is also the result of all imperative functions (e.g. <code>printf</code>) or of all expressions that do not logically return any value (assignment or e.g. loop). This means that if you write:</p> <pre><code>if x &gt; 0 then printfn "Big!" </code></pre> <p>... then the expression is well-typed, because <code>printfn "Big!"</code> has a return type <code>unit</code> and the implicitly added <code>else</code> branch also returns <code>unit</code>. You can create a value of type <code>unit</code> directly by hand (the type has exactly one value), so the above actually corresponds to:</p> <pre><code>if x &gt; 0 then printfn "Big!" else () </code></pre> <p>From the C# perspective, it makes more sense to read <code>if .. then .. else</code> as the conditional operator:</p> <pre><code>x/2 + (x%2 == 0 ? 0 : 1) </code></pre>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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