F# For Dummys - Day 5

57 阅读1分钟

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

let name = "Lucy"

can we change our name? let's try to rename our string variable

let name = "Lucy"
name <- "Lily"
printfn $"{name}"

image.png the error message on the Problems window:

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

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 its sugguestion:

let mutable name = "Lucy"
name <- "Lily"
printfn $"{name}"

run the code, name has been changed successfully!

image.png conclusion:
all the variables we define in F# is immutable by default, we need to explicitly add 'mutable' before variables, if we want to 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"

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

let mutable name = "Lucy"
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"

output:

image.png