Fsharp-maps
提供:Dev Guides
F#-マップ
F#では、マップは値をキーに関連付ける特別な種類のセットです。 マップは、セットが作成されるのと同様の方法で作成されます。
マップを作成する
Map.emptyを使用して空のマップを作成し、Add関数を使用してアイテムを追加すると、マップが作成されます。 次の例はこれを示しています-
例
( *Create an empty Map* )
let students =
Map.empty. ( *Creating an empty Map* )
Add("Zara Ali", "1501").
Add("Rishita Gupta", "1502").
Add("Robin Sahoo", "1503").
Add("Gillian Megan", "1504");;
printfn "Map - students: %A" students
( *Convert a list to Map* )
let capitals =
[ "Argentina", "Buenos Aires";
"France ", "Paris";
"Chili", "Santiago";
"Malaysia", " Kuala Lumpur";
"Switzerland", "Bern" ]
|> Map.ofList;;
printfn "Map capitals : %A" capitals
あなたがプログラムをコンパイルして実行すると、次の出力が得られます-
Map - students: map
[("Gillian Megan", "1504"); ("Rishita Gupta", "1502"); ("Robin Sahoo", "1503
");
("Zara Ali", "1501")]
Map capitals : map
[("Argentina", "Buenos Aires"); ("Chili", "Santiago"); ("France ", "Paris");
("Malaysia", " Kuala Lumpur"); ("Switzerland", "Bern")]
キーを使用して、マップ内の個々の要素にアクセスできます。
例
( *Create an empty Map* )
let students =
Map.empty. ( *Creating an empty Map* )
Add("Zara Ali", "1501").
Add("Rishita Gupta", "1502").
Add("Robin Sahoo", "1503").
Add("Gillian Megan", "1504");;
printfn "Map - students: %A" students
(*Accessing an element using key *)
printfn "%A" students.["Zara Ali"]
あなたがプログラムをコンパイルして実行すると、次の出力が得られます-
Map - students: map
[("Gillian Megan", "1504"); ("Rishita Gupta", "1502"); ("Robin Sahoo", "1503
");
("Zara Ali", "1501")]
"1501"
マップの基本操作
モジュール名を追加
次の表は、マップの基本操作を示しています-
Member | Description |
---|---|
Add | Returns a new map with the binding added to the given map. |
ContainsKey | Tests if an element is in the domain of the map. |
Count | The number of bindings in the map. |
IsEmpty | Returns true if there are no bindings in the map. |
Item | Lookup an element in the map. Raises KeyNotFoundException if no binding exists in the map. |
Remove | Removes an element from the domain of the map. No exception is raised if the element is not present. |
TryFind | Lookup an element in the map, returning a Some *value if the element is in the domain of the map and None* if not. |
次の例は、上記の機能のいくつかの使用を示しています-
例
( *Create an empty Map* )
let students =
Map.empty. ( *Creating an empty Map* )
Add("Zara Ali", "1501").
Add("Rishita Gupta", "1502").
Add("Robin Sahoo", "1503").
Add("Gillian Megan", "1504").
Add("Shraddha Dubey", "1505").
Add("Novonil Sarker", "1506").
Add("Joan Paul", "1507");;
printfn "Map - students: %A" students
printfn "Map - number of students: %d" students.Count
(* finding the registration number of a student*)
let found = students.TryFind "Rishita Gupta"
match found with
| Some x -> printfn "Found %s." x
| None -> printfn "Did not find the specified value."
あなたがプログラムをコンパイルして実行すると、次の出力が得られます-
Map - students: map
[("Gillian Megan", "1504"); ("Joan Paul", "1507"); ("Novonil Sarker", "1506"
);
("Rishita Gupta", "1502"); ("Robin Sahoo", "1503");
("Shraddha Dubey", "1505"); ("Zara Ali", "1501")]
Map - number of students: 7
Found 1502.