f-sharp
  1. f-sharp-boolean-operators

F# Boolean Operators

Boolean operators in F# are used to compare and manipulate the truth value of logical expressions. In this tutorial, we will discuss the various Boolean operators available in F# with examples.

Syntax

The following are the Boolean operators available in F#:

  • && (logical AND operator)
  • || (logical OR operator)
  • not (logical NOT operator)

The syntax for using these Boolean operators in F# is:

expression1 && expression2
expression1 || expression2
not expression

Example

Here's an example of using the &&, ||, and not operators in F#:

let x = 42
let y = 10

if x > 30 && y > 5 then
    printfn "Both expressions are true"
else
    printfn "At least one expression is false"

if x > 50 || y > 20 then
    printfn "At least one expression is true"
else
    printfn "Both expressions are false"

if not (x = y) then
    printfn "x is not equal to y"
else
    printfn "x is equal to y"

Output

The output of the above example would be:

Both expressions are true
At least one expression is true
x is not equal to y

Explanation

  • The && operator returns true if both the expressions it connects are true, and false otherwise.
  • The || operator returns true if any of the expressions it connects are true, and false only if both expressions are false.
  • The not operator reverses the truth value of the expression it connects. If the expression is true, not returns false, and if the expression is false, not returns true.

Use

Boolean operators are useful in various situations, such as:

  • in conditional statements, to check if certain expressions are true or false
  • in loops, to control the iteration based on the truth value of certain expressions
  • in functions, to return different values based on certain conditions

Important Points

  • Always remember to use parentheses to group expressions when using Boolean operators to avoid ambiguity.
  • Boolean operators always return Boolean values - either true or false.
  • The not operator has the highest precedence among the Boolean operators.

Summary

In this tutorial, we learned about the various Boolean operators available in F# - &&, ||, and not. We also saw examples of using these operators to manipulate the truth value of expressions. Finally, we discussed the importance of using parentheses to group expressions and the precedence of the not operator.

Published on: