List F#变量赋值的键值对列表
给定键/值对列表:List F#变量赋值的键值对列表,list,variables,f#,List,Variables,F#,给定键/值对列表: do [("A", 1);("B",2)] |> (fun list -> for item in list do match item with | ("A", x) -> //expression assigning x to variable "A" | ("B", x) -> //expression as
do
[("A", 1);("B",2)]
|> (fun list ->
for item in list do
match item with
| ("A", x) -> //expression assigning x to variable "A"
| ("B", x) -> //expression assigning x to variable "B"
| _ -> //default expression
)
有没有一些表达我可以写,将完成相同的事情
let A = 1
let B = 2
我事先知道列表中的项不超过10个,并且这些项是元组,但不知道是否存在“A”或“B”或其他键,或者列表是否为空
基本上,将列表分解为一组类型化变量
更新:背景说明
在我的应用程序中,我从另一个团队维护的上游程序中收到一个键/值对列表,就像这样。我希望列表中包含某些键,我希望将这些键分配给类型化变量以供以后处理。如果缺少我需要的异常,我将抛出一个异常。但是,我不想被锁定在任何给定的变量名集合中,除了预期的变量名。对于所有这些变量,我希望能够在运行时分配它们。如果您想在代码的后面对变量做些什么,那么它们将需要在范围内-因此您将不可避免地以某种方式声明变量。最简单的选择是使其可变,并根据列表中的值对其进行可变:
let mutable A = 0
let mutable B = 0
为了使变异更容易,您可以使用setter创建一个查找表:
let setters =
dict [ ("A", fun x -> A <- x); ("B", fun x -> B <- x) ]
由于你的问题的背景有限,很难说这是否是一种实现问题动机的好方法——作为F#code,它看起来确实有点难看,如果你添加更多的背景,有人可以提出更好的方法。听起来您有一些动态数据可以很好地表示为地图:
let data = Map [ ("A", 1); ("B", 2) ]
let a = Map.find "A" data
// throws an exception if "A" is not present
let b = Map.find "B" data
// throws an exception if "B" is not present
let c = Map.tryFind "C" data
// "C" is not present so c = None
注意:在F#中,约定绑定名称(变量名称)以小写字母开头。为什么要这样做?之后你会如何处理它们?为原始postnice添加了一些上下文!那很好!
let data = Map [ ("A", 1); ("B", 2) ]
let a = Map.find "A" data
// throws an exception if "A" is not present
let b = Map.find "B" data
// throws an exception if "B" is not present
let c = Map.tryFind "C" data
// "C" is not present so c = None