DEV Community

Cover image for F# For Dummys - Day 5 Mutable
AllenZhu
AllenZhu

Posted on • Updated on

F# For Dummys - Day 5 Mutable

Today we learn how to change the value of variable(not variable actually)
remember how to define a value

let name = "Lucy"
Enter fullscreen mode Exit fullscreen mode

can we change our name? let's try to change the value of our string variable

let name = "Lucy"
name <- "Lily"
printfn $"{name}"
Enter fullscreen mode Exit fullscreen mode

Run, whoops, compile error
Image description

the error message on the Problems window:

This value is not mutable. Consider using the mutable keyword, e.g. 'let mutable name = expression'.(2,1)</br>
Enter fullscreen mode Exit fullscreen mode

obviously, change value of name is not allowed
luckily, the error message is clear and friendly, it even suggest how to fix the problem
let's try it's sugguestion:

let mutable name = "Lucy"
name <- "Lily"
printfn $"{name}"
Enter fullscreen mode Exit fullscreen mode

run the code, name has been changed successfully!

Image description

conclusion:
value we define in F# is immutable by default, we need to explicitly add 'mutable' before value, now we can call it variables, as we can change it's value later

Let's do a practice:
my name is Lucy, I'm 14 year's old

let name = "Lucy"
let age = 14
printfn $"my name is {name}, I'm {age} years old"
Enter fullscreen mode Exit fullscreen mode

my sister is Lily, she's 11 year's old, please introduce herself for Lily without define new values
answer:

let mutable name = "Lucy" // name is variable now
let mutable age = 14
printfn $"my name is {name}, I'm {age} years old"
name <- "Lily"
age <- 11
printfn $"my name is {name}, I'm {age} years old"
Enter fullscreen mode Exit fullscreen mode

output:
Image description

Top comments (0)