Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 37 ยท Language Basics

F# Operators, Precedence and Type Conversion

Learn F# arithmetic, comparison, boolean, bitwise and string operators, operator precedence, custom operators, and how to convert between types with int, float, string and parse functions.

Operators in F# are ordinary functions with symbolic names, which is why you can pass them around and even define your own. This lesson lists the operators you will use daily, explains precedence, shows how to parse text safely into numbers, and recaps explicit conversions between types.

Arithmetic

Operator Meaning Example Result
+ - * add, subtract, multiply 6 * 7 42
/ divide (integer division for ints) 9 / 2 4
% remainder 9 % 2 1
** power (floats) 2.0 ** 10.0 1024.0
-x negate -(3) -3

Both operands must have the same type. pown raises integers to an integer power: pown 2 10 is 1024. Built-in functions abs, min, max, sqrt, sin, exp, log, ceil, floor, round are all in scope without opening anything.

Comparison and equality

FSHARP
1 = 1        // true  (equality, a single equals sign)
1 <> 2       // true
3 > 2        // true
"a" < "b"    // true, strings compare alphabetically
compare 3 5  // -1  (returns negative, zero or positive)

F# equality is structural: two lists, tuples or records are equal when their contents are equal. You do not need to override anything:

FSHARP
[ 1; 2; 3 ] = [ 1; 2; 3 ]        // true
(1, "a") = (1, "a")              // true

Reference equality exists as obj.ReferenceEquals(a, b) and is rarely needed.

Boolean operators

&& (and), || (or) and not. They short-circuit, so x <> 0 && 10 / x > 1 never divides by zero.

Bitwise operators

Operator Meaning
&&& bitwise and
||| bitwise or
^^^ bitwise xor
~~~ bitwise not
<<< shift left
>>> shift right
FSHARP
printfn "%d" (0b1100 &&& 0b1010)   // 8
printfn "%d" (0b1100 ||| 0b1010)   // 14
printfn "%d" (1 <<< 4)             // 16

Pipeline and composition operators

Three symbols deserve special mention because they define the F# style. They get a full lesson in Pipelines and composition:

  • x |> f passes x to f.
  • f >> g builds a new function that runs f and then g.
  • f <| x applies f to x (the reverse pipe, rare).

Precedence in short

Highest to lowest, roughly: function application, **, * / %, + -, comparison operators, &&, ||, then |> and assignment <-. Function application binds tighter than anything else, so f x + 1 means (f x) + 1. When in doubt, add parentheses: they cost nothing and the next reader will thank you.

FSHARP
let a = 2 + 3 * 4          // 14
let b = (2 + 3) * 4        // 20
let c = abs -5 + 1         // 6, because abs -5 is applied first

Converting between types

Numeric conversion functions are named after the target type: int, int64, float, decimal, byte, char, string.

FSHARP
int 3.9            // 3 (truncates, no rounding)
int "42"           // 42 (parses!)
float 7            // 7.0
string 3.5         // "3.5"
char 65            // 'A'

Be careful: int "abc" throws FormatException. For input from users or files, parse safely with TryParse, which returns a success flag and a value. F# turns that pattern into a tuple, and the standard idiom is to match it:

FSHARP
let parseAge (text: string) =
    match System.Int32.TryParse text with
    | true, value -> Some value
    | false, _ -> None

printfn "%A" (parseAge "36")      // Some 36
printfn "%A" (parseAge "abc")     // None

Some and None belong to the option type, which gets a full chapter later in this course. (For now, read it as "a value or nothing".)

Custom operators

Wrap the symbol in parentheses to define it:

FSHARP
let (+++) (a: string) (b: string) = a + " " + b
let sentence = "functional" +++ "programming"

Operators can also be given to higher-order functions: List.reduce (+) [1;2;3] is 6, because (+) is just the addition function. Use custom operators sparingly; a well-named function is usually clearer.

Casting between object types

For types in an inheritance hierarchy you use :> (upcast, always safe) and :?> (downcast, may fail at run time):

FSHARP
let o = "text" :> obj
let s = o :?> string

Type tests use :? in a pattern: match o with :? string as s -> .... These are most useful for .NET interop, covered in Chapter 8.

Try it in C#

C# stand-ins show the same truncation, safe parsing and short-circuiting. The TryParse call mirrors the F# tuple pattern exactly.

C# C# stand-in: safe parsing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# C# stand-in: short-circuit and precedence

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does 9 / 2 evaluate to in F#?

    Both operands are ints, so the division is integer division and truncates.
  2. 2. Which operator tests two values for inequality?

    F# uses <> for 'not equal'.
  3. 3. What does int 3.9 return?

    Converting a float to int truncates toward zero.
  4. 4. Which is the safest way to turn user input into an int?

    TryParse reports failure instead of throwing an exception.

Summary

  • Operators are functions; both operands need the same type.
  • = is structural equality, <> is inequality, bitwise operators use triple symbols (&&&, |||, ^^^).
  • Application binds tightest; use parentheses to be clear.
  • Convert with int, float, string and friends; parse untrusted text with TryParse.
  • :> upcasts and :?> downcasts.

Next: Conditionals and loops