- .NET Core 2.0 By Example
- Rishabh Verma Neha Shrivastava
- 282字
- 2021-06-24 18:30:58
Variable declaration
F# uses the let keyword for the declaration of a variable, for example:
let square x = x*x
The compiler automatically detects this as a value type. If we pass a float value, the compiler will be able to understand that without declaring a data type. Variables in F# are immutable, so once a value is assigned to a variable, it can't be changed. They are compiled as static read-only properties.
The following example demonstrates this:
let x:int32 = 50
let y:int32 = 30
let z:int32 = x + y
Variables x, y, and z are all of type int32 and are immutable, meaning their value cannot be changed.
Let's print their values. The syntax is as follows:
printfn "x: %i" x
printfn "y: %i" y
printfn "z: %i" z
After the preceding code executes, the result is as follows:
x: 50
y: 30
z: 80
Now, suppose we want to modify the value of x from 50 to 60 and check that z reflects the updated sum; we will write the code as:
let x = 60
let y = 30
let z = x + y
On executing this code, we get the following errors, and rightly so because x and z are immutable:
Duplicate definition of value 'x'
Duplicate definition of value 'z'
The correct way of doing it would be to use mutable variables for the declaration, as shown here:
let mutable x = 60
let y = 30 //It's optional to make y mutable.
let mutable z = x + y
x <- 70
z <- x + y
On printing the values again, we will see:
x: 70
y: 30
z: 100
- 軟件工程基礎(chǔ)教程
- App草圖+流程圖+交互原型設(shè)計(jì)教程
- 掌握分布式跟蹤:微服務(wù)和復(fù)雜系統(tǒng)性能分析
- 產(chǎn)品眾包設(shè)計(jì)理論與方法
- 軟件研發(fā)效能提升之美
- Unity AR/VR開發(fā):從新手到專家
- 區(qū)塊鏈核心算法解析
- Spring Cloud微服務(wù)快速上手
- 深入淺出Spring Boot 3.x
- 深入理解Prometheus監(jiān)控系統(tǒng)
- 軟件平臺(tái)架構(gòu)設(shè)計(jì)與技術(shù)管理之道
- Java核心技術(shù)·卷Ⅰ:基礎(chǔ)知識(shí)(原書第10版)
- DDD工程實(shí)戰(zhàn):從零構(gòu)建企業(yè)級DDD應(yīng)用
- 移山之道:VSTS軟件開發(fā)指南
- 物流倉諸配送系統(tǒng)技巧450問