View Category
Define an empty map
clojure
(def m {})
cpp
Hashtable^ hash = gcnew Hashtable;
Generic::Dictionary<String^, String^>^ dict = gcnew Generic::Dictionary<String^, String^>();
std::map<int, std::string> m;
erlang
Map = dict:new(),
Map = orddict:new(),
Map = gb_trees:empty(),
Map = ets:new(the_map_name, [set, private, {keypos, 1}]),
fantom
map := [:]
fsharp
let map = Map.empty
let map = new Generic.Dictionary<string, string>()
let map = new Hashtable()
groovy
def map = [:]
Map map = new HashMap();
haskell
import qualified Data.Map as M
emptyMap = M.empty
emptyMap = M.empty
java
Map map = new HashMap();
ocaml
module StringMap = Map.Make (String)
let m = StringMap.empty
let m = StringMap.empty
let m = Hashtbl.create 42
perl
# %map = {}
# This was wrong, that would have created a hash with one key
# of the stringified hash reference (HASH(0xNUMBERSHERE)) and a
# value of 'undef', as well as triggering a
# "Reference found where even-sized list expected" with the warnings
# pragma enabled
my %map;
# This was wrong, that would have created a hash with one key
# of the stringified hash reference (HASH(0xNUMBERSHERE)) and a
# value of 'undef', as well as triggering a
# "Reference found where even-sized list expected" with the warnings
# pragma enabled
my %map;
php
$map = array();
$map = array("" => "");
python
map = {}
ruby
map = {}
scala
val map = mutable.Map.empty
val map = mutable.HashMap.empty[String, Int]
val map = Map()
Define an unmodifiable empty map
clojure
; Clojure maps are immutable
(def m {})
(def m {})
cpp
const std::map<T1,T2> immutable_map_instance_of_type_t1_to_t2;
erlang
% Erlang data structures are immutable - updating a 'map' sees a modified copy created
Map = dict:new(),
% Erlang data structures are immutable - updating a 'map' sees a modified copy created
Map = dict:new(),
fantom
map := [:].ro
fsharp
// Most native fsharp data structures are immutable - updating a 'map' sees a modified copy created
let map = Map.empty
let map = Map.empty
groovy
empty = Collections.EMPTY_MAP
map = [:].asImmutable()
def empty = MapUtils.EMPTY_SORTED_MAP
def empty = ImmutableMap.of()
haskell
import qualified Data.Map as Map
output :: Map.Map k v
output = Map.empty
output :: Map.Map k v
output = Map.empty
java
Map empty = Collections.EMPTY_MAP;
SortedMap empty = MapUtils.EMPTY_SORTED_MAP;
ocaml
(* OCaml maps are functional data structures (so are immutable) *)
module StringMap = Map.Make (String)
let m = StringMap.empty
module StringMap = Map.Make (String)
let m = StringMap.empty
perl
# perl does not provide unmodifiable maps/hashes, but you could use "constant
# functions", if you really need them
# 2011-07-06 Not actually true, see Hash::Util::lock_hash;
sub MAP () { {} }
# functions", if you really need them
# 2011-07-06 Not actually true, see Hash::Util::lock_hash;
sub MAP () { {} }
use Hash::Util qw/lock_hash/;
# two lines
my %hash;
lock_hash(%hash);
# or in one line
lock_hash(my %locked_hash);
# two lines
my %hash;
lock_hash(%hash);
# or in one line
lock_hash(my %locked_hash);
php
/* It's not possible to define an array as a constant
* Instead we can use the serialize-function */
$fruits = array("apple", "banana", "orange");
define("FRUITS", serialize($fruits));
echo FRUITS; // a:3:{i:0;s:5:"apple";i:1;s:6:"banana";i:2;s:6:"orange";}
$my_fruits = unserialize(FRUITS); // and normal array again
* Instead we can use the serialize-function */
$fruits = array("apple", "banana", "orange");
define("FRUITS", serialize($fruits));
echo FRUITS; // a:3:{i:0;s:5:"apple";i:1;s:6:"banana";i:2;s:6:"orange";}
$my_fruits = unserialize(FRUITS); // and normal array again
python
import collections
EmptyDict = collections.namedtuple("EmptyDict", "")
e = EmptyDict()
EmptyDict = collections.namedtuple("EmptyDict", "")
e = EmptyDict()
ruby
map = {}.freeze
scala
val map = immutable.Map.empty
val map = immutable.TreeMap.empty[String, Int]
val map = Map()
Define an initial map
Define the map
{circle:1, triangle:3, square:4}
clojure
(def m '{circle 1 triangle 1 square 4})
cpp
Hashtable^ shapes = gcnew Hashtable;
shapes->Add("circle", 1);
shapes->Add("triangle", 3);
shapes->Add("square", 4);
shapes->Add("circle", 1);
shapes->Add("triangle", 3);
shapes->Add("square", 4);
Generic::Dictionary<String^, int>^ shapes = gcnew Generic::Dictionary<String^, int>();
shapes->Add("circle", 1);
shapes->Add("triangle", 3);
shapes->Add("square", 4);
shapes->Add("circle", 1);
shapes->Add("triangle", 3);
shapes->Add("square", 4);
map<string, int> shapes;
shapes["circle"] = 1;
shapes["triangle"] = 3;
shapes["square"] = 4;
shapes["circle"] = 1;
shapes["triangle"] = 3;
shapes["square"] = 4;
erlang
Map = dict:from_list([{circle, 1}, {triangle, 3}, {square, 4}]),
Map0 = dict:new(),
% Erlang variables are 'single-assignment' i.e. they cannot be reassigned
Map1 = dict:store(circle, 1, Map0),
Map2 = dict:store(triangle, 3, Map1),
Map3 = dict:store(square, 4, Map2),
% Erlang variables are 'single-assignment' i.e. they cannot be reassigned
Map1 = dict:store(circle, 1, Map0),
Map2 = dict:store(triangle, 3, Map1),
Map3 = dict:store(square, 4, Map2),
Map0 = gb_trees:empty(),
Map1 = gb_trees:enter(circle, 1, Map0),
Map2 = gb_trees:enter(triangle, 3, Map1),
Map3 = gb_trees:enter(square, 4, Map2),
Map1 = gb_trees:enter(circle, 1, Map0),
Map2 = gb_trees:enter(triangle, 3, Map1),
Map3 = gb_trees:enter(square, 4, Map2),
Map = gb_trees:from_orddict(lists:keysort(1, [{circle, 1}, {triangle, 3}, {square, 4}])),
Map = ets:new(the_map_name, [ordered_set, private, {keypos, 1}]),
ets:insert(Map, [{circle, 1}, {triangle, 3}, {square, 4}]),
ets:insert(Map, [{circle, 1}, {triangle, 3}, {square, 4}]),
fantom
map := ["circle":1, "triangle":2, "square":4]
fsharp
let shapes = Map.ofList [("circle", 1); ("triangle", 3); ("square", 4)]
let shapes = Map.empty.Add("circle", 1).Add("triangle", 3).Add("square", 4)
let shapes = new Generic.Dictionary<string, int>()
shapes.Add("circle", 1)
shapes.Add("triangle", 3)
shapes.Add("square", 4)
shapes.Add("circle", 1)
shapes.Add("triangle", 3)
shapes.Add("square", 4)
let shapes = Map [("circle", 1); ("triangle", 3); ("square", 4)]
groovy
shapes = [circle:1, triangle:3, square:4]
// if you require a specific type of map ...
LinkedHashMap shapes1 = [circle:1, triangle:3, square:4]
Properties shapes2 = [circle:1, triangle:3, square:4]
TreeMap shapes3 = [circle:1, triangle:3, square:4]
shapes4 = [circle:1, triangle:3, square:4] as ConcurrentHashMap // as variation
LinkedHashMap shapes1 = [circle:1, triangle:3, square:4]
Properties shapes2 = [circle:1, triangle:3, square:4]
TreeMap shapes3 = [circle:1, triangle:3, square:4]
shapes4 = [circle:1, triangle:3, square:4] as ConcurrentHashMap // as variation
haskell
import qualified Data.Map as M
initialMap = M.fromList [("circle", 1), ("triangle", 3), ("square", 4)]
initialMap = M.fromList [("circle", 1), ("triangle", 3), ("square", 4)]
java
Map shapes = new HashMap();
shapes.put("circle", 1);
shapes.put("triangle", 3);
shapes.put("square", 4);
shapes.put("circle", 1);
shapes.put("triangle", 3);
shapes.put("square", 4);
Map shapes = new HashMap() {{ put("circle",1); put("triangle",3); put("square",4); }}
ocaml
module StringMap = Map.Make (String)
let m0 = StringMap.empty
let m1 = StringMap.add "circle" 1 m0
let m2 = StringMap.add "triangle" 3 m1
let m3 = StringMap.add "square" 4 m2
let m0 = StringMap.empty
let m1 = StringMap.add "circle" 1 m0
let m2 = StringMap.add "triangle" 3 m1
let m3 = StringMap.add "square" 4 m2
let m = Hashtbl.create 42;;
Hashtbl.replace m "circle" 1;;
Hashtbl.replace m "triangle" 3;;
Hashtbl.replace m "square" 4;;
Hashtbl.replace m "circle" 1;;
Hashtbl.replace m "triangle" 3;;
Hashtbl.replace m "square" 4;;
perl
%map = (circle => 1, triangle => 3, square => 4);
php
$map = array("circle" => 1, "triangle" => 3, "square" => 4);
python
shapes = {'circle': 1, 'square': 4, 'triangle': 2}
ruby
shapes = {'circle'=>1, 'triangle'=>3, 'square'=>4}
shapes = Hash['circle', 1, 'triangle', 3, 'square', 4]
shapes = { :circle => 1, :triangle => 3, :square => 4 }
scala
val shapes = immutable.TreeMap("circle" -> 1, "triangle" -> 3, "square" -> 4)
val shapes = mutable.Map.empty[String, Int]
shapes += "circle" -> 1
shapes += "triangle" -> 3
shapes += "square" -> 4
shapes += "circle" -> 1
shapes += "triangle" -> 3
shapes += "square" -> 4
var shapes = immutable.Map.empty[String, Int]
shapes = shapes + ("circle" -> 1)
shapes = shapes + ("triangle" -> 3)
shapes = shapes + ("square" -> 4)
shapes = shapes + ("circle" -> 1)
shapes = shapes + ("triangle" -> 3)
shapes = shapes + ("square" -> 4)
val shapes = immutable.Map(
"circle" -> 1,
"triangle" -> 3,
"square" -> 4
)
"circle" -> 1,
"triangle" -> 3,
"square" -> 4
)
val map = Map("circle" -> 1, "triangle" -> 3, "square" -> 4)
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"))
(println "ok"))
cpp
if (pets->ContainsKey("mary")) Console::WriteLine("ok");
if (pets.find("mary") != pets.end()){
std::cout << "ok" << std::endl;
}
std::cout << "ok" << std::endl;
}
if (pets.count("mary") > 0)
cout << "ok" << endl;
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")
if (map.containsKey("mary")) echo("ok")
fsharp
if (Map.mem "mary" pets) then printfn "ok"
if pets.ContainsKey("mary") then printfn "ok"
groovy
pets = [joe:'cat', mary:'turtle', bill:'canary']
if(pets.containsKey('mary')) println 'ok'
if(pets.containsKey('mary')) println 'ok'
pets = [joe:'cat', mary:'turtle', bill:'canary']
if(pets.mary) println 'ok'
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")
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 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"
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'});
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 $pets{mary};
print 'ok' if exists $pets{mary}
php
if (array_key_exists("mary", $pets)) {
echo "ok";
}
echo "ok";
}
if (isset($pets["mary"])) { // only works if $pets["mary"] can't be false or 0
echo "ok";
}
echo "ok";
}
python
pets = dict(joe='cat', mary='turtle', bill='canary')
if ("mary" in pets) print "ok"
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))
(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")
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
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)
groovy
pets = [joe:'cat', mary:'turtle', bill:'canary']
assert pets['joe'] == 'cat'
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
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 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."
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};
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")
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
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 pets = StringMap.add "rob" "dog" StringMap.empty
let () =
let map = Hashtbl.create 42 in
Hashtbl.replace map "rob" "dog"
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))
; 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);
}
{
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")
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
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"
groovy
pets = [joe:'cat', mary:'turtle', bill:'canary']
println pets.remove('bill')
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
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 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
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;
echo $last;
$last = $pets[count($pets)-1];
echo $last;
unset($last);
echo $last;
unset($last);
$bill = $pets["bill"];
echo $bill;
unset($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 => "***" })
Create a histogram map from a list
Given the list
[a,b,a,c,b,b], produce a map {a:2, b:3, c:1} which contains the count of each unique item in the list
clojure
(let [l '[a b a c b b]]
(loop [m {}
d (distinct l)]
(let [item (first d)]
(if (zero? (count d))
m
(recur
(assoc m
item
(count
(filter #(= item %) l)))
(rest d))))))
(loop [m {}
d (distinct l)]
(let [item (first d)]
(if (zero? (count d))
m
(recur
(assoc m
item
(count
(filter #(= item %) l)))
(rest d))))))
(->> [:a :b :a :c :b :b]
(group-by identity)
(reduce (fn [m e] (assoc m (first e) (count (second e)))) {}))
(group-by identity)
(reduce (fn [m e] (assoc m (first e) (count (second e)))) {}))
(reduce conj {} (for [[x xs] (group-by identity "abacbb")] [x (count xs)]))
(frequencies ["a","b","a","c","b","b"])
(frequencies '[a b a c b b])
cpp
for each(String^ entry in input) hash[entry] = hash->ContainsKey(entry)
? Convert::ToInt32(hash[entry]->ToString()) + 1 : 1;
? Convert::ToInt32(hash[entry]->ToString()) + 1 : 1;
for each(String^ entry in input) dict[entry] = dict->ContainsKey(entry) ? dict[entry] + 1 : 1;
map<string,int> hist;
for (auto e: { "a","b","a","c","b","b" })
++hist[e];
for (auto e: hist)
cout << e.first << " : " << e.second << endl;
for (auto e: { "a","b","a","c","b","b" })
++hist[e];
for (auto e: hist)
cout << e.first << " : " << e.second << endl;
erlang
% Imperative Solution
Histogram = histogram(List),
Histogram = histogram(List),
% Functional (1) Solution
Histogram = histogram(List),
Histogram = histogram(List),
lists:foldl(fun(Elem, OldDict) ->
dict:update_counter(Elem, 1, OldDict)
end,
dict:new(),
[a,b,a,c,b,b])).
dict:update_counter(Elem, 1, OldDict)
end,
dict:new(),
[a,b,a,c,b,b])).
fantom
list := ["a","b","a","c","b","b"]
map := [Str:Int][:]
list.each |Str s, Int i| { if(!map.containsKey(s)) map.add(s,1); else map[s] = ++map[s] }
echo (map)
map := [Str:Int][:]
list.each |Str s, Int i| { if(!map.containsKey(s)) map.add(s,1); else map[s] = ++map[s] }
echo (map)
fsharp
let histogram = (List.foldLeft (fun (acc : Map<char, int>) (e : char) -> if (Map.mem e acc) then (Map.add e ((Map.find e acc) + 1) acc) ; else (Map.add e 1 acc)) (Map.empty) list)
let histogram list =
let rec histogram' list' dict' =
match list' with
| [] -> dict'
| x :: xs ->
match Map.tryFind x dict' with
| Some(Value) -> histogram' xs (Map.add x (Value + 1) dict')
| None -> histogram' xs (Map.add x 1 dict')
histogram' list Map.empty
// ------
let histogram' = histogram list
let rec histogram' list' dict' =
match list' with
| [] -> dict'
| x :: xs ->
match Map.tryFind x dict' with
| Some(Value) -> histogram' xs (Map.add x (Value + 1) dict')
| None -> histogram' xs (Map.add x 1 dict')
histogram' list Map.empty
// ------
let histogram' = histogram list
let histogram = (List.foldLeft (fun (acc : Generic.Dictionary<char, int>) (e : char) -> (if acc.ContainsKey(e) then acc.[e] <- acc.[e] + 1 ; else acc.Add(e, 1)) ; acc) (new Generic.Dictionary<char, int>()) list)
let histogram =
list
|> Seq.groupBy (fun a -> a)
|> Seq.map(fun (key, elements) -> key, Seq.length elements)
|> Map.ofSeq
list
|> Seq.groupBy (fun a -> a)
|> Seq.map(fun (key, elements) -> key, Seq.length elements)
|> Map.ofSeq
groovy
histogram = [:]
list.each { item ->
if (!histogram.containsKey(item)) histogram[item] = 0
histogram[item]++
}
list.each { item ->
if (!histogram.containsKey(item)) histogram[item] = 0
histogram[item]++
}
histogram = [:]
list.each { histogram[it] = (histogram[it] ?: 0) + 1 }
list.each { histogram[it] = (histogram[it] ?: 0) + 1 }
haskell
import Data.List
import qualified Data.Map as Map
histogram :: Ord a => [a] -> Map.Map a Int
histogram xs = Map.fromList [ (head l, length l) | l <- group (sort xs) ]
output :: Map.Map String Int
output = histogram ["a","b","a","c","b","b"]
import qualified Data.Map as Map
histogram :: Ord a => [a] -> Map.Map a Int
histogram xs = Map.fromList [ (head l, length l) | l <- group (sort xs) ]
output :: Map.Map String Int
output = histogram ["a","b","a","c","b","b"]
import Control.Arrow
import Data.List
import qualified Data.Map as Map
import System.Random
histogram :: Ord a => [a] -> Map.Map a Int
histogram = Map.fromList . map (head &&& length) . group . sort
main = print . histogram . take 1000 . randomRs (1::Int, 100) =<< newStdGen
import Data.List
import qualified Data.Map as Map
import System.Random
histogram :: Ord a => [a] -> Map.Map a Int
histogram = Map.fromList . map (head &&& length) . group . sort
main = print . histogram . take 1000 . randomRs (1::Int, 100) =<< newStdGen
java
Map map = new HashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
String s = (String) it.next();
if (!map.containsKey(s)) {
map.put(s, new Integer(1));
} else {
map.put(s, new Integer(((Integer)map.get(s)).intValue() + 1));
}
}
for (Iterator it = list.iterator(); it.hasNext();) {
String s = (String) it.next();
if (!map.containsKey(s)) {
map.put(s, new Integer(1));
} else {
map.put(s, new Integer(((Integer)map.get(s)).intValue() + 1));
}
}
LinkedMap histogram = new LinkedMap();
for (Object letter : list)
histogram.put(letter, !histogram.containsKey(letter) ? 1 : MapUtils.getIntValue(histogram, letter) + 1);
for (Object letter : list)
histogram.put(letter, !histogram.containsKey(letter) ? 1 : MapUtils.getIntValue(histogram, letter) + 1);
ocaml
module StringMap = Map.Make (String)
let histogram lst =
List.fold_left (fun m v ->
let n =
if StringMap.mem v m
then succ (StringMap.find v m)
else 1
in
StringMap.add v n m
) StringMap.empty lst
let () =
let h = histogram ["a"; "b"; "a"; "c"; "b"; "b"] in
StringMap.iter (fun key value ->
Printf.printf " %s: %d\n" key value
) h
let histogram lst =
List.fold_left (fun m v ->
let n =
if StringMap.mem v m
then succ (StringMap.find v m)
else 1
in
StringMap.add v n m
) StringMap.empty lst
let () =
let h = histogram ["a"; "b"; "a"; "c"; "b"; "b"] in
StringMap.iter (fun key value ->
Printf.printf " %s: %d\n" key value
) h
perl
foreach(@list) {
$histogram{$_}++;
}
$histogram{$_}++;
}
$histogram{$_}++ for @list;
php
$list = array("a","b","a","c","b","b");
$map = array_count_values($list);
$map = array_count_values($list);
python
from collections import defaultdict
h = defaultdict(int)
for k in "abacbb":
h[k] += 1
h = {}
for k in "abacbb":
h[k] = h.setdefault(k, 0) + 1
h = defaultdict(int)
for k in "abacbb":
h[k] += 1
h = {}
for k in "abacbb":
h[k] = h.setdefault(k, 0) + 1
from collections import Counter
h = Counter("abacbb")
print(h)
h = Counter("abacbb")
print(h)
ruby
histogram = {}
list.each { |item| histogram[item] = (histogram[item] || 0) +1 }
list.each { |item| histogram[item] = (histogram[item] || 0) +1 }
list = %w{a b a c b b}
histogram = list.each_with_object(Hash.new(0)) do |item, hash|
hash[item] += 1
end
p histogram # => {"a"=>2, "b"=>3, "c"=>1}
histogram = list.each_with_object(Hash.new(0)) do |item, hash|
hash[item] += 1
end
p histogram # => {"a"=>2, "b"=>3, "c"=>1}
list.inject(Hash.new(0)) {|h, item| h[item] += 1; h}
scala
list.groupBy(identity).mapValues(_.size)
list foreach { (x) => histogram += x -> (histogram.getOrElse(x, 0) + 1) }
val data = List("a", "b", "a", "c", "b", "b")
val keys = data removeDuplicates
val hist = Map.empty[String, Int] ++ keys.map{ k => (k, (data count (_==k)))}
assert(hist == Map("a"->2, "b"->3, "c"->1))
val keys = data removeDuplicates
val hist = Map.empty[String, Int] ++ keys.map{ k => (k, (data count (_==k)))}
assert(hist == Map("a"->2, "b"->3, "c"->1))
val histEntries = for {
key <- data.removeDuplicates
count = data.count(_ == key)
} yield (key -> count)
val hist = Map(histEntries: _*)
key <- data.removeDuplicates
count = data.count(_ == key)
} yield (key -> count)
val hist = Map(histEntries: _*)
value.foldLeft(Map[T, Int]()){
(m, c) => m.updated(c, m.getOrElse(c, 0) + 1)
}
(m, c) => m.updated(c, m.getOrElse(c, 0) + 1)
}
list.groupBy(identity).mapValues(_.size)
Categorise a list
Given the list
[one, two, three, four, five] produce a map {3:[one, two], 4:[four, five], 5:[three]} which sorts elements into map entries based on their length
clojure
(loop [m {}
l ["one" "two" "three" "four" "five"]]
(if (zero? (count l))
m
(let [item (first l)
key (count item)]
(recur
(assoc m key (cons item (get m key [])))
(rest l)))))
l ["one" "two" "three" "four" "five"]]
(if (zero? (count l))
m
(let [item (first l)
key (count item)]
(recur
(assoc m key (cons item (get m key [])))
(rest l)))))
(group-by count ["one" "two" "three" "four" "five"])
cpp
for each(String^ entry in input)
{
key = entry->Length;
if (!hash->ContainsKey(key)) hash[key] = gcnew ArrayList;
safe_cast<ArrayList^>(hash[key])->Add(entry);
}
{
key = entry->Length;
if (!hash->ContainsKey(key)) hash[key] = gcnew ArrayList;
safe_cast<ArrayList^>(hash[key])->Add(entry);
}
erlang
% Imperative Solution
CatList = categorise(List),
CatList = categorise(List),
% Functional (1) Solution
CatList = categorise(List),
CatList = categorise(List),
fantom
list := ["one", "two", "three", "four", "five"]
map := [Int:List][:]
list.each { List l := map[it.size] ?: [,]; map[it.size] = l.add(it) }
echo(map)
map := [Int:List][:]
list.each { List l := map[it.size] ?: [,]; map[it.size] = l.add(it) }
echo(map)
fsharp
let catmap = (List.foldLeft (fun (acc : Map<int, List<string> >) (e : string) -> if (Map.mem e.Length acc) then (Map.add e.Length ((Map.find e.Length acc) @ [e]) acc) ; else (Map.add e.Length [e] acc)) (Map.empty) list)
let lengthMap =
["one"; "two"; "three"; "four"; "five"]
|> Seq.groupBy (fun s -> s.Length)
|> Seq.map (fun (length, entries) -> (length, entries |> List.ofSeq))
|> Map.ofSeq
["one"; "two"; "three"; "four"; "five"]
|> Seq.groupBy (fun s -> s.Length)
|> Seq.map (fun (length, entries) -> (length, entries |> List.ofSeq))
|> Map.ofSeq
groovy
map = ['one', 'two', 'three', 'four', 'five'].groupBy{ it.size() }
haskell
import qualified Data.Map as Map
groupInMapBy :: Ord k => (a -> k) -> [a] -> Map.Map k [a]
groupInMapBy f = foldr (\a -> Map.insertWith (++) (f a) [a]) Map.empty
output :: Map.Map Int [String]
output = groupInMapBy length ["one", "two", "three", "four", "five"]
groupInMapBy :: Ord k => (a -> k) -> [a] -> Map.Map k [a]
groupInMapBy f = foldr (\a -> Map.insertWith (++) (f a) [a]) Map.empty
output :: Map.Map Int [String]
output = groupInMapBy length ["one", "two", "three", "four", "five"]
import Data.List (groupBy, sortBy)
import Data.Function (on)
groupInPairsBy :: Ord k => (a -> k) -> [a] -> [(k, [a])]
groupInPairsBy f = map (\xs -> (f (head xs), xs)) .
groupBy ((==) `on` f) . sortBy (compare `on` f)
output :: [(Int, [String])]
output = groupInPairsBy length ["one", "two", "three", "four", "five"]
import Data.Function (on)
groupInPairsBy :: Ord k => (a -> k) -> [a] -> [(k, [a])]
groupInPairsBy f = map (\xs -> (f (head xs), xs)) .
groupBy ((==) `on` f) . sortBy (compare `on` f)
output :: [(Int, [String])]
output = groupInPairsBy length ["one", "two", "three", "four", "five"]
java
SortedMap<Integer, List<String> > map = new TreeMap<Integer, List<String> >(); int key; List<String> vlist;
for (String item : list)
{
key = item.length(); vlist = map.containsKey(key) ? map.get(key) : new ArrayList<String>();
vlist.add(item); map.put(key, vlist);
}
for (String item : list)
{
key = item.length(); vlist = map.containsKey(key) ? map.get(key) : new ArrayList<String>();
vlist.add(item); map.put(key, vlist);
}
MultiValueMap map = new MultiValueMap();
for (Object item : list) map.put(((String) item).length(), item);
for (Object item : list) map.put(((String) item).length(), item);
ocaml
let map =
List.fold_left (fun map v ->
let len = String.length v in
let before =
try IntMap.find len map
with Not_found -> [] in
IntMap.add len (v :: before) map
) IntMap.empty ["one"; "two"; "three"; "four"; "five"]
List.fold_left (fun map v ->
let len = String.length v in
let before =
try IntMap.find len map
with Not_found -> [] in
IntMap.add len (v :: before) map
) IntMap.empty ["one"; "two"; "three"; "four"; "five"]
perl
@list = qw(one two three four five);
push @{$map{length($_)}}, $_ for (@list);
push @{$map{length($_)}}, $_ for (@list);
php
foreach ($array as $m) {
$l = strlen($m);
$map[$l][] = $m;
}
arsort($map);
$l = strlen($m);
$map[$l][] = $m;
}
arsort($map);
python
c = defaultdict(list)
for k in ["one", "two", "four", "three", "five"]:
c[len(k)].append(k)
for k in ["one", "two", "four", "three", "five"]:
c[len(k)].append(k)
from itertools import groupby
lst = ["one", "two", "four", "three", "five"]
c = dict((k, list(g)) for k,g in
groupby(sorted(lst, key=lambda x: len(x)), key=lambda x: len(x)))
print(c)
lst = ["one", "two", "four", "three", "five"]
c = dict((k, list(g)) for k,g in
groupby(sorted(lst, key=lambda x: len(x)), key=lambda x: len(x)))
print(c)
ruby
lengths = {}
list.each do |x|
len = x.size
lengths[len] = (lengths[len] || [])
lengths[len] << x
end
list.each do |x|
len = x.size
lengths[len] = (lengths[len] || [])
lengths[len] << x
end
lengths = list.group_by {|x| x.size}
list.inject({}) { |h,x| (h[x.size]||=[]) << x; h }
scala
list foreach { (x) => map += x.length -> (x :: map.getOrElse(x.length, Nil)) }
list foreach { (x) => map += x.length -> (map.getOrElse(x.length, Nil) ::: List(x)) }
List("one", "two", "three", "four", "five") groupBy (_ size)
