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
- 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.
- Create a value
x
using thelet
keyword, and assign something to it (anything will do). - 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.
- Create a mutable value,
y
, and assign something to it. - What happens when you change the value of
y
with the assignment operator?
let mutable y = 10;;
Work with different F# types
- Reset the REPL.
- Explore some of the other values you can create such as
string
s,double
s andboolean
s. Remember that the type is inferred based on the value being assigned. - 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.
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;;
- Remember that it does not use index placeholder values (such as
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
- Reset your REPL.
- Assign two integer values.
let x = 10 let y = 20;;
- 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
- Create a third
float
value and attempt to add it to one of the integers. What happens?let z = 42.0 x + z;;
- 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;;
- Or turn the second number into an integer.
x + int z;;
- Try some other F# math operators to play with the REPL.