最简单的定义和使用全局变量的方法

时间:2015-06-24 08:04:12

标签: variables f# global

chat_index.html

我需要使用变量“ident”。

我只需要将变量值从测试的第一部分传递给第二部分......

我想问你是否有任何简单的方法来定义和使用全局变量,或者即使你有更好(也很容易)的想法

请记住,我是初学者,所以我更喜欢比较容易的人。

3 个答案:

答案 0 :(得分:4)

全局变量通常会使您的代码难以使用 - 特别是如果它们是可变的。

相反,会考虑返回您需要跟踪的值作为复合值。一个简单的数据类型开始将是一个元组:

let ``first part`` id =
    let someOtherValue = "Foo"
    someOtherValue, id + 1

此函数将int(当前ID)作为输入,并返回string * int(第一个元素为string的元组,第二个元素和{{1 }})作为输出。

您可以这样称呼它:

int

请注意,您可以使用模式匹配立即将值解构为两个命名符号:> let other, newId = ``first part`` 42;; val other : string = "Foo" val newId : int = 43 other

您的第二个功能也可以将ID作为输入:

newId

您可以使用上面的let ``second part`` id otherArgument = // use id here, if you need it "Bar" 值来调用它:

newId

如果您发现自己这么做了,可以为此目的定义一条记录:

> let result = ``second part`` newId "Baz";;

val result : string = "Bar"

现在你可以开始定义高阶函数来处理这种类型,例如type Identifiable<'a> = { Id : int; Value : 'a } 函数:

map

这是一个函数,它将一个可识别的module Identifiable = let map f x = { Id = x.Id; Value = f x.Value } // Other functions go here... 从一个值映射到另一个值,但保留了该身份。

以下是使用它的简单示例:

Value

如您所见,它会保留值> let original = { Id = 42; Value = "1337" };; val original : Identifiable<string> = {Id = 42; Value = "1337";} > let result' = original |> Identifiable.map System.Int32.Parse;; val result' : Identifiable<int> = {Id = 42; Value = 1337;} ,但会将42Value更改为string

如果您想这样做,您仍然可以明确更改ID:

int

答案 1 :(得分:3)

由于这已经失去了评论,这就是我如何做一个例子

let mutable t = 0

let first =
    t <- 1 + 1
    //other stuff

let second = 
    //can use t here and it will have a value of 2

在某些情况下,您必须使用ref:

let t = ref 0

let first =
    t := 1 + 1
    //other stuff

let second = 
    //can use t here and it will have a value of 2 - 
    // you use "!t" to get the value

答案 2 :(得分:1)

如果您在文件顶部定义ident,请执行以下操作:

let ident = "foo" 

// rest of your code using ident 

ident是全局的,您可以在文件的下一部分中使用。

编辑:

如果ident在代码的下一部分中发生更改,请使用以下命令:

let ident = ref "foo"
相关问题