View Subcategory
Check if a key exists in a map
Given a map pets
{joe:cat,mary:turtle,bill:canary} print "ok" if an pet exists for "mary"
fsharp
if (Map.mem "mary" pets) then printfn "ok"
if pets.ContainsKey("mary") then printfn "ok"
fantom
map := ["joe":"cat", "mary":"turtle", "bill":"canary"]
if (map.containsKey("mary")) echo("ok")
if (map.containsKey("mary")) echo("ok")
go
m := map[string]string{ "joe": "cat", "mary": "turtle", "bill": "canary" }
if _, ok := m["mary"]; ok {
fmt.Println("ok")
}
if _, ok := m["mary"]; ok {
fmt.Println("ok")
}
Retrieve a value from a map
Given a map pets
{joe:cat,mary:turtle,bill:canary} print the pet for "joe" ("cat")
fsharp
if (Map.mem "joe" pets) then printfn "%s" (Map.find "joe" pets)
if (pets |> Map.exists (fun key _ -> key = "joe")) then printfn "%s" (Map.find "joe" pets)
let key = "joe"
match (pets |> Map.tryfind key) with
| Some(value) -> printfn "%s" value
| None -> printfn "Key %s not found" key
match (pets |> Map.tryfind key) with
| Some(value) -> printfn "%s" value
| None -> printfn "Key %s not found" key
if pets.ContainsKey("joe") then printfn "%s" pets.["joe"]
if pets.ContainsKey("joe") then printfn "%s" (pets.["joe"] :?> string)
fantom
map := ["joe":"cat", "mary":"turtle", "bill":"canary"]
pet := map["joe"]
echo("pet=$pet")
pet := map["joe"]
echo("pet=$pet")
go
fmt.Println(pets["joe"])
Add an entry to a map
Given an empty pets map, add the mapping from
"rob" to "dog"
fsharp
pets <- (Map.add "rob" "dog" pets)
pets.Add("rob", "dog")
fantom
map["rob"] = "dog"
go
pets["rob"] = "dog"
Remove an entry from a map
Given a map pets
{joe:cat,mary:turtle,bill:canary} remove the mapping for "bill" and print "canary"
fsharp
let key = "bill"
match (pets |> Map.tryFind key) with
| Some(value) -> pets <- (Map.remove key pets) ; printfn "%s : %s removed" key value
| None -> printfn "Key %s not found" key
match (pets |> Map.tryFind key) with
| Some(value) -> pets <- (Map.remove key pets) ; printfn "%s : %s removed" key value
| None -> printfn "Key %s not found" key
let key = "bill"
let entry = if (pets.ContainsKey(key)) then Some(pets.[key]) ; else None
pets.Remove(key)
match entry with
| Some(value) -> printfn "%s" value
| None -> printfn "key not found"
let entry = if (pets.ContainsKey(key)) then Some(pets.[key]) ; else None
pets.Remove(key)
match entry with
| Some(value) -> printfn "%s" value
| None -> printfn "key not found"
fantom
pet := map.remove("bill")
echo ("pet=$pet")
echo ("pet=$pet")
go
fmt.Println(pets["bill"])
delete(pets, "bill")
delete(pets, "bill")
fmt.Println(pets["bill"])
pets["bill"] = "", false
pets["bill"] = "", false
