官术网_书友最值得收藏!

  • .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
主站蜘蛛池模板: 金塔县| 凤城市| 保靖县| 合江县| 杭州市| 白沙| 西藏| 宁化县| 茂名市| 玉门市| 桑日县| 望江县| 新干县| 通江县| 府谷县| 娄底市| 焦作市| 鸡泽县| 万州区| 登封市| 东阳市| 庐江县| 秦皇岛市| 白山市| 承德县| 滕州市| 临安市| 邵阳市| 安国市| 怀集县| 荥经县| 平昌县| 龙山县| 阆中市| 山西省| 遵化市| 海宁市| 富平县| 那曲县| 湘潭市| 杭州市|