Introduction to F#

Duration

10 minutes

Lab Goals

The primary goal of this lab will be to gain a deeper understanding of mutable and immutable values.

Steps

F# is immutable by default

  1. Make sure your REPL window is open and visible, and reset it if you are continuing from the prior exercise in order to clear existing values.
  2. Create a value x using the let keyword, and assign something to it (anything will do).
  3. Use the assignment operator "<-" and try to change the value of x to something else. What happened? Why?

Working with mutable types

In the prior exercise, you appeared to change a value through the let keyword. However, when you issued the second let statement, you really created a new value in memory. In this part we will change the value.

  1. Create a mutable value, y, and assign something to it.
  2. let mutable y = 10;;
  3. What happens when you change the value of y with the assignment operator?

Work with different F# types

  1. Reset the REPL.
  2. Explore some of the other values you can create such as strings, doubles and booleans. Remember that the type is inferred based on the value being assigned.
  3. Output your values with printfn using a format string
    • Remember that it does not use index placeholder values (such as {0}, {1}), but instead has unique identifiers for the types - %s for strings, %i for integers, etc.
    • Also, remember we use spaces to separate parameters.
    Here's an example:
    let num = 10
    let text = "Hello"
    let bestVal = 42.0
    let flag = true
    printfn "The values are: %i, %s, %.2f, and %b" num text bestVal flag;;
Note: when entering multiple statements into the REPL, you can put the terminating double-semicolon at the end of the final statement.

Performing mathematical operations

  1. Reset your REPL.
  2. Assign two integer values.
    let x = 10
    let y = 20;;
  3. Add the two numbers together - you can just type the expression into the REPL, or assign it to a new value if you prefer, either will work.
    x + y
  4. Create a third float value and attempt to add it to one of the integers. What happens?
    let z = 42.0
    x + z;;
  5. The numbers are not the same type, and therefore cannot be manipulated together - however we can turn either one into the other type. F# has functions which performs basic casting. For example, you can turn your first number into a float:
    float x + z;;
  6. Or turn the second number into an integer.
    x + int z;;
  7. Try some other F# math operators to play with the REPL.

Summary

In this lab, we have begun to work with mutable and immutable values and used some of the math operators.
Go Back