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}]),
haskell
import qualified Data.Map as M
emptyMap = M.empty
emptyMap = M.empty
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(),
haskell
import qualified Data.Map as Map
output :: Map.Map k v
output = Map.empty
output :: Map.Map k v
output = Map.empty
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}]),
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)]
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.
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")
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.
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
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).
haskell
import qualified Data.Map as M
pets = M.insert "rob" "dog" M.empty
pets = M.insert "rob" "dog" M.empty
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]),
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
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
csharp
using System.Collections.Generic;
using System.Linq;
// This is a "functional" C# approach
// NOTE: In C# "maps" are of type Dictionary<Tkey, TValue>
// so our histogram map is of type Dictionary<object, int>
public class HistogramMap {
public Dictionary<object, int> FromList(List<object> list) {
// The "Aggregate" method works like "inject" in many other languages.
return list.Aggregate(
new Dictionary<object, int>(),
(map, obj) => {
// If this is the first time we've seen this obj, set the count to 0
if (!map.ContainsKey(obj)) map[obj] = 0;
// Increment the count
map[obj]++;
// Return the map for the next iteration.
// NOTE: This does NOT return from our "FromList" method
return map;
}
);
}
public static void Main() {
// Create our Histogram Map from a new list
var map = new HistogramMap().FromList(
new List<object>() { 'a', 'b', 'a', 'c', 'b', 'b' }
);
// This just prints the result
System.Console.WriteLine (
string.Join (", ",
// "Select" works like "map" or "collect" in many other languages
map.Select( kvp =>
string.Format("{0} : {1}", kvp.Key, kvp.Value)
).ToArray()
)
);
}
}
using System.Linq;
// This is a "functional" C# approach
// NOTE: In C# "maps" are of type Dictionary<Tkey, TValue>
// so our histogram map is of type Dictionary<object, int>
public class HistogramMap {
public Dictionary<object, int> FromList(List<object> list) {
// The "Aggregate" method works like "inject" in many other languages.
return list.Aggregate(
new Dictionary<object, int>(),
(map, obj) => {
// If this is the first time we've seen this obj, set the count to 0
if (!map.ContainsKey(obj)) map[obj] = 0;
// Increment the count
map[obj]++;
// Return the map for the next iteration.
// NOTE: This does NOT return from our "FromList" method
return map;
}
);
}
public static void Main() {
// Create our Histogram Map from a new list
var map = new HistogramMap().FromList(
new List<object>() { 'a', 'b', 'a', 'c', 'b', 'b' }
);
// This just prints the result
System.Console.WriteLine (
string.Join (", ",
// "Select" works like "map" or "collect" in many other languages
map.Select( kvp =>
string.Format("{0} : {1}", kvp.Key, kvp.Value)
).ToArray()
)
);
}
}
new[] {"a","b","a","c","b","b"}
.GroupBy(s => s)
.Select(s => new { Value = s.Key, Count = s.Count() })
.ToList()
.ForEach(e => Console.WriteLine("{0} : {1} ", e.Value, e.Count));
.GroupBy(s => s)
.Select(s => new { Value = s.Key, Count = s.Count() })
.ToList()
.ForEach(e => Console.WriteLine("{0} : {1} ", e.Value, e.Count));
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])).
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
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
csharp
using System.Collections.Generic;
using System.Linq;
public class ListCategorizer {
public static void Main() {
var list = new List<string>() { "one", "two", "three", "four", "five" };
var categories = list.GroupBy(el => el.Length)
.ToDictionary( g => g.Key, // key
g => g.ToList() ); // value
}
}
using System.Linq;
public class ListCategorizer {
public static void Main() {
var list = new List<string>() { "one", "two", "three", "four", "five" };
var categories = list.GroupBy(el => el.Length)
.ToDictionary( g => g.Key, // key
g => g.ToList() ); // value
}
}
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),
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"]
