变量是指给我们的程序可以操作的存储区域的名称.每个变量都有一个特定的类型,它决定了变量内存的大小和布局;可以存储在该存储器中的值的范围;以及可以应用于变量的操作集.
F#中的变量声明
let 关键字是用于变量声明 :
例如,
let x = 10
它声明一个变量x并为其赋值10.
您还可以为变量&minus分配表达式;
let x = 10let y = 20let z = x + y
以下示例说明概念 :
示例
let x = 10let y = 20let z = x + yprintfn "x: %i" xprintfn "y: %i" yprintfn "z: %i" z
当你编译并执行程序时,它会产生followi ng输出 :
x: 10y: 20z: 30
F#中的变量不可变,这意味着一旦变量绑定到某个值,就无法更改.它们实际上被编译为静态只读属性.
以下示例演示了这一点.
示例
let x = 10let y = 20let z = x + yprintfn "x: %i" xprintfn "y: %i" yprintfn "z: %i" zlet x = 15let y = 20let z = x + yprintfn "x: %i" xprintfn "y: %i" yprintfn "z: %i" z
当您编译并执行程序时,它会显示以下错误消息 :
Duplicate definition of value 'x'Duplicate definition of value 'Y'Duplicate definition of value 'Z'
带类型声明的变量定义
变量定义告诉编译器在哪里和多少s应该创建变量的torage.变量定义可以指定数据类型,并包含该类型的一个或多个变量的列表,如以下示例所示.
示例
let x:int32 = 10let y:int32 = 20let z:int32 = x + yprintfn "x: %d" xprintfn "y: %d" yprintfn "z: %d" zlet p:float = 15.99let q:float = 20.78let r:float = p + qprintfn "p: %g" pprintfn "q: %g" qprintfn "r: %g" r
编译并执行程序时,它显示以下错误消息 :
x: 10y: 20z: 30p: 15.99q: 20.78r: 36.77
可变变量
有时您需要更改存储在变量中的值.要指定声明和赋值变量的值可能发生更改,在程序的后续部分中,F#提供 mutable 关键字.您可以使用此关键字声明和分配可变变量,其值将更改.
mutable 关键字允许您在可变变量中声明和赋值.
您可以使用 let 关键字为可变变量指定一些初始值.但是,要为其分配新的后续值,您需要使用← 运算符.
例如,
let mutable x = 10x ← 15
以下示例将清除概念 :
示例
et mutable x = 10let y = 20let mutable z = x + yprintfn "Original Values:"printfn "x: %i" xprintfn "y: %i" yprintfn "z: %i" zprintfn "Let us change the value of x"printfn "Value of z will change too."x <- 15z <- x + yprintfn "New Values:"printfn "x: %i" xprintfn "y: %i" yprintfn "z: %i" z
当您编译并执行程序时,它会产生以下输出 :
Original Values:x: 10y: 20z: 30Let us change the value of xValue of z will change too.New Values:x: 15y: 20z: 35