"first part" &&&& fun _ ->
let ident
"second part" &&&& fun _ ->
ident ....
我需要使用变量“ident”。
我只需要将变量值从测试的第一部分传递到第二部分...
我想问您是否有任何简单的方法来定义和使用全局变量,或者即使您有更好(且简单)的想法来做到这一点
请记住,我是初学者,所以我更喜欢简单的。
最佳答案
全局变量通常会使您的代码难以使用 - 特别是当它们是可变的时。
相反,考虑将需要跟踪的值作为复合值返回。元组是一种简单的数据类型:
let ``first part`` id =
let someOtherValue = "Foo"
someOtherValue, id + 1
此函数采用 int
(当前 ID)作为输入,并返回 string * int
(一个元组,其中第一个元素是 string
code>,第二个元素和 int
) 作为输出。
你可以这样调用它:
> let other, newId = ``first part`` 42;;
val other : string = "Foo"
val newId : int = 43
请注意,您可以使用模式匹配将值立即解构为两个命名符号:other
和 newId
。
您的第二个函数也可以将 ID 作为输入:
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;}
如您所见,它保留了值 42
,但将 Value
从 string
更改为 int
.
如果您愿意,您仍然可以显式更改 ID:
> let result'' = { result' with Id = 7 };;
val result'' : Identifiable<int> = {Id = 7;
Value = 1337;}
关于variables - 定义和使用全局变量的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31021025/