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"
clojure
(if (contains? '{joe cat mary turtle bill canary} 'mary)
(println "ok"))
cpp
if (pets->ContainsKey("mary")) Console::WriteLine("ok");
if (pets.find("mary") != pets.end()){
std::cout << "ok" << std::endl;
}
if (pets.count("mary") > 0)
cout << "ok" << endl;
erlang
dict:is_key(mary, Pets) andalso begin io:format("ok~n"), true end.
IsMember = ets:member(Pets, mary), if (IsMember) -> io:format("ok~n") ; true -> false end.
case gb_trees:lookup(mary, Pets) of none -> false ; _ -> io:format("ok~n") end.
fantom
map := ["joe":"cat", "mary":"turtle", "bill":"canary"]
if (map.containsKey("mary")) echo("ok")
fsharp
if (Map.mem "mary" pets) then printfn "ok"
if pets.ContainsKey("mary") then printfn "ok"
go
m := map[string]string{ "joe": "cat", "mary": "turtle", "bill": "canary" }
if _, ok := m["mary"]; ok {
fmt.Println("ok")
}
groovy
pets = [joe:'cat', mary:'turtle', bill:'canary']
if(pets.containsKey('mary')) println 'ok'
pets = [joe:'cat', mary:'turtle', bill:'canary']
if(pets.mary) println 'ok'
haskell
import qualified Data.Map as M
import Control.Monad (when)

pets = M.fromList [("joe", "cat"), ("mary", "turtle"), ("bill", "canary")]

checkMary = when (M.member "mary" pets) (print "ok")

java
if (pets.containsKey("mary")) System.out.println("ok");
ocaml
module StringMap = Map.Make (String)

let map =
List.fold_left (fun map (key, value) ->
StringMap.add key value map
) StringMap.empty [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")]

let () =
if StringMap.mem "mary" map
then print_endline "OK"
let () =
let map = Hashtbl.create 42 in
List.iter (fun (key, value) ->
Hashtbl.add map key value
) [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")];

if Hashtbl.mem map "mary" then print_endline "OK"
perl
%pets = (joe => 'cat', mary => 'turtle', bill => 'canary');
print 'ok' if ($pets{'mary'});
%pets = (joe => 'cat', mary => 'turtle', bill => 'canary');
print 'ok' if $pets{'mary'};
print 'ok' if $pets{mary};
print 'ok' if exists $pets{mary}
php
if (array_key_exists("mary", $pets)) {
echo "ok";
}
if (isset($pets["mary"])) { // only works if $pets["mary"] can't be false or 0
echo "ok";
}
python
pets = dict(joe='cat', mary='turtle', bill='canary')
if ("mary" in pets) print "ok"
ruby
puts "ok" if map.has_key?('mary')
puts "ok" if map['mary'] # Only works if map entry can't be nil or false
scala
if (pets.contains("mary")) println("ok")
map.get("mary").foreach(println("ok"))

Retrieve a value from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print the pet for "joe" ("cat")
clojure
(def pets '{joe cat mary turtle bill canary})

(println (get pets 'joe))
cpp
if (pets->ContainsKey("joe")) Console::WriteLine(pets["joe"]);
cout << pets["joe"] << endl;
erlang
dict:is_key(joe, Pets) andalso begin io:format("~w~n", [dict:fetch(joe, Pets)]), true end.
case dict:find(joe, Pets) of error -> false ; {ok, Pet} -> io:format("~w~n", [Pet]) end.
IsMember = ets:member(Pets, joe), if (IsMember) -> io:format("~w~n", [ets:lookup_element(Pets, joe, 2)]) ; true -> false end.
case ets:match(Pets, {joe, '$1'}) of [] -> false ; [[Pet]] -> io:format("~w~n", [Pet]) end.
case gb_trees:lookup(joe, Pets) of none -> false ; {value, Pet} -> io:format("~w~n", [Pet]) end.
fantom
map := ["joe":"cat", "mary":"turtle", "bill":"canary"]
pet := map["joe"]
echo("pet=$pet")
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
if pets.ContainsKey("joe") then printfn "%s" pets.["joe"]
if pets.ContainsKey("joe") then printfn "%s" (pets.["joe"] :?> string)
go
fmt.Println(pets["joe"])
groovy
pets = [joe:'cat', mary:'turtle', bill:'canary']
assert pets['joe'] == 'cat'
assert pets.joe == 'cat'
haskell
import qualified Data.Map as M

pets = M.fromList [("joe", "cat"), ("mary", "turtle"), ("bill", "canary")]
retrieve = print $ M.findWithDefault "Not found" "joe" pets
java
String pet = pets.get("joe");
ocaml
module StringMap = Map.Make (String)

let map =
List.fold_left (fun map (key, value) ->
StringMap.add key value map
) StringMap.empty [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")]

let () =
try
let pet = StringMap.find "joe" map in
Printf.printf "Joe's pet is a %s.\n" pet
with Not_found ->
prerr_endline "No pet found for Joe."
let () =
let map = Hashtbl.create 42 in
List.iter (fun (key, value) ->
Hashtbl.add map key value
) [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")];

try
let pet = Hashtbl.find map "joe" in
Printf.printf "Joe's pet is a %s.\n" pet
with Not_found ->
prerr_endline "No pet found for Joe."
perl
%pets = (joe => 'cat', mary => 'turtle', bill=>'canary');
print $pets{joe};
php
echo $pets["joe"];
python
print pets['joe']
ruby
puts map['joe']
scala
if (pets.contains("joe")) println(pets("joe"))
println(pets.getOrElse("joe", "*** no pet owned ***"))
pets("joe")

Add an entry to a map

Given an empty pets map, add the mapping from "rob" to "dog"
clojure
(assoc {} 'rob 'dog)
cpp
pets->Add("rob", "dog");
pets["rob"] = "dog";
erlang
Pets1 = dict:store(rob, dog, Pets0).
ets:insert(Pets, {rob, dog}).
Pets1 = gb_trees:enter(rob, dog, Pets0).
fantom
map["rob"] = "dog"
fsharp
pets <- (Map.add "rob" "dog" pets)
pets.Add("rob", "dog")
go
pets["rob"] = "dog"
groovy
pets['rob'] = 'dog'
pets.rob = 'dog'
pets.put('rob', 'dog')
haskell
import qualified Data.Map as M

pets = M.insert "rob" "dog" M.empty
java
pets.put("rob", "dog");
ocaml
module StringMap = Map.Make (String)

let pets = StringMap.add "rob" "dog" StringMap.empty
let () =
let map = Hashtbl.create 42 in
Hashtbl.replace map "rob" "dog"
perl
$pets{rob} = 'dog';
php
$pets["rob"] = "dog";
python
pets['rob'] = 'dog'
ruby
pets['rob']='dog'
scala
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"
clojure
; Maps are immutable
; The following expression will return a new map without the 'bill key
(let [pets '{joe cat mary turtle bill canary}]
(println (get pets 'bill))
(dissoc pets 'bill))
cpp
if (pets->ContainsKey("bill"))
{
String^ value = safe_cast<String^>(pets["bill"]); pets->Remove("bill");
Console::WriteLine("{0}", value);
}
erlang
Pet = dict:fetch(bill, Pets0), Pets1 = dict:erase(bill, Pets0), io:format("~w~n", [Pet]),
Pet = ets:lookup_element(Pets, bill, 2), ets:delete(Pets, bill), io:format("~w~n", [Pet]),
{value, Pet} = gb_trees:lookup(bill, Pets0), Pets1 = gb_trees:delete(bill, Pets0), io:format("~w~n", [Pet]),
fantom
pet := map.remove("bill")
echo ("pet=$pet")
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
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"
go
fmt.Println(pets["bill"])
delete(pets, "bill")
fmt.Println(pets["bill"])
pets["bill"] = "", false
groovy
pets = [joe:'cat', mary:'turtle', bill:'canary']
println pets.remove('bill')
haskell
import qualified Data.Map as M

main = do
let pets = M.fromList [("joe", "cat"), ("mary", "turtle"), ("bill", "canary")]
pets2 = M.delete "bill" pets
print $ maybe "" id (M.lookup "bill" pets)
print pets2
java
System.out.println(pets.remove("bill"))
ocaml
module StringMap = Map.Make (String)

let pets =
List.fold_left (fun map (key, value) ->
StringMap.add key value map
) StringMap.empty [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")]

let get_and_rem key m =
try
let value = StringMap.find key m in
let rm = StringMap.remove key m in
Some (value, rm)
with Not_found ->
None

let () =
let key = "bill" in
match get_and_rem key pets with
| Some (found, new_pets) ->
Printf.printf "%s : %s removed\n" key found
| None ->
Printf.printf "Key %s not found" key
let get_and_rem m key =
try
let value = Hashtbl.find m key in
Hashtbl.remove m key;
Some value
with Not_found ->
None

let () =
let pets = Hashtbl.create 42 in
List.iter (fun (key, value) ->
Hashtbl.add pets key value
) [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")];

let key = "bill" in
match get_and_rem pets key with
| Some found ->
Printf.printf "%s : %s removed\n" key found
| None ->
Printf.printf "Key %s not found" key
perl
print delete $pets{bill};
php
$last = array_pop($pets); // removes last key and assign it to the variable
echo $last;
$last = $pets[count($pets)-1];
echo $last;
unset($last);
$bill = $pets["bill"];
echo $bill;
unset($bill);
print_r(array_pop($pets));
python
print pets.pop('bill')
ruby
puts map.delete :bill
scala
val pet = pets("bill") ; pets -= "bill" ; println(pet)
println(pets.removeKey("bill") match { case Some(pet) => pet ; case None => "***" })