简体   繁体   中英

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).

I'm obviously new at F# but this is giving me a headache so I hope someone can help me out.

In F#, assignment (to change the value of a mutable variable) is written using <- rather than using = (which means just equality testing). 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 :

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 . Here, the new state is a new map extended with the key-value pair k,v .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM