[英]F# Append custom table with custom list
I'm trying to make a function that extends a symbolTable with a list of Decl 我试图使该延伸的符号表与申报的列表功能
Definitions: 定义:
type Typ = |Integer
|Boolean
|Ft of Typ list * Typ;;
type Decl = string * Typ;;
type symbolTable = Map<string, Typ>;;
I'm trying to do it the following way: 我正在尝试以下方式:
let extendST (st: symbolTable) (lst: Decl list) : symbolTable =
let mutable returnValue = st
for (x,y) in lst do
returnValue = returnValue.Add(x,y)
returnValue;;
But apparently nothing is being added to the returnValue (the function returns the same symbolTable as is being input). 但显然没有任何东西被添加到returnValue(该函数返回与输入相同的symbolTable)。
I'm obviously new at F# but this is giving me a headache so I hope someone can help me out. 我显然是F#的新人,但这让我头疼,所以我希望有人可以帮助我。
In F#, assignment (to change the value of a mutable
variable) is written using <-
rather than using =
(which means just equality testing). 在F#中,赋值(更改
mutable
变量的值)是使用<-
而不是使用=
(这意味着只是相等测试)来编写的。 Your code is comparing the two values and then ignoring the result (which is valid, but not what you wanted). 您的代码正在比较这两个值,然后忽略结果(这是有效的,但不是您想要的)。 The corrected version looks like this:
更正后的版本如下所示:
let extendST (st: symbolTable) (lst: Decl list) : symbolTable =
let mutable returnValue = st
for (x,y) in lst do
returnValue <- returnValue.Add(x,y)
returnValue
However, if you are looking for a functional solution, you can write this using fold
: 但是,如果您正在寻找功能性解决方案,可以使用
fold
编写:
let extendST (st: symbolTable) (lst: Decl list) : symbolTable =
lst |> List.fold (fun map (k, v) -> Map.add k v map) st
The fold
function takes some state (your symbol table) and calculates a new state for each element of a given list lst
. 在
fold
功能需要一定的状态(您的符号表),并计算给定列表中的每个元素的新状态lst
。 Here, the new state is a new map extended with the key-value pair k,v
. 这里,新状态是用键值对
k,v
扩展的新映射。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.