1defmodule Map do 2 @moduledoc """ 3 Maps are the "go to" key-value data structure in Elixir. 4 5 Maps can be created with the `%{}` syntax, and key-value pairs can be 6 expressed as `key => value`: 7 8 iex> %{} 9 %{} 10 iex> %{"one" => :two, 3 => "four"} 11 %{3 => "four", "one" => :two} 12 13 Key-value pairs in a map do not follow any order (that's why the printed map 14 in the example above has a different order than the map that was created). 15 16 Maps do not impose any restriction on the key type: anything can be a key in a 17 map. As a key-value structure, maps do not allow duplicated keys. Keys are 18 compared using the exact-equality operator (`===/2`). If colliding keys are defined 19 in a map literal, the last one prevails. 20 21 When the key in a key-value pair is an atom, the `key: value` shorthand syntax 22 can be used (as in many other special forms): 23 24 iex> %{a: 1, b: 2} 25 %{a: 1, b: 2} 26 27 If you want to mix the shorthand syntax with `=>`, the shorthand syntax must come 28 at the end: 29 30 iex> %{"hello" => "world", a: 1, b: 2} 31 %{:a => 1, :b => 2, "hello" => "world"} 32 33 Keys in maps can be accessed through some of the functions in this module 34 (such as `Map.get/3` or `Map.fetch/2`) or through the `map[]` syntax provided 35 by the `Access` module: 36 37 iex> map = %{a: 1, b: 2} 38 iex> Map.fetch(map, :a) 39 {:ok, 1} 40 iex> map[:b] 41 2 42 iex> map["non_existing_key"] 43 nil 44 45 To access atom keys, one may also use the `map.key` notation. Note that `map.key` 46 will raise a `KeyError` if the `map` doesn't contain the key `:key`, compared to 47 `map[:key]`, that would return `nil`. 48 49 map = %{foo: "bar", baz: "bong"} 50 map.foo 51 #=> "bar" 52 map.non_existing_key 53 ** (KeyError) key :non_existing_key not found in: %{baz: "bong", foo: "bar"} 54 55 > Note: do not add parens when accessing fields, such as in `data.key()`. 56 > If parenthesis are used, Elixir will expect `data` to be an atom representing 57 > a module and attempt to call the *function* `key/0` in it. 58 59 The two syntaxes for accessing keys reveal the dual nature of maps. The `map[key]` 60 syntax is used for dynamically created maps that may have any key, of any type. 61 `map.key` is used with maps that hold a predetermined set of atoms keys, which are 62 expected to always be present. Structs, defined via `defstruct/1`, are one example 63 of such "static maps", where the keys can also be checked during compile time. 64 65 Maps can be pattern matched on. When a map is on the left-hand side of a 66 pattern match, it will match if the map on the right-hand side contains the 67 keys on the left-hand side and their values match the ones on the left-hand 68 side. This means that an empty map matches every map. 69 70 iex> %{} = %{foo: "bar"} 71 %{foo: "bar"} 72 iex> %{a: a} = %{:a => 1, "b" => 2, [:c, :e, :e] => 3} 73 iex> a 74 1 75 76 But this will raise a `MatchError` exception: 77 78 %{:c => 3} = %{:a => 1, 2 => :b} 79 80 Variables can be used as map keys both when writing map literals as well as 81 when matching: 82 83 iex> n = 1 84 1 85 iex> %{n => :one} 86 %{1 => :one} 87 iex> %{^n => :one} = %{1 => :one, 2 => :two, 3 => :three} 88 %{1 => :one, 2 => :two, 3 => :three} 89 90 Maps also support a specific update syntax to update the value stored under 91 *existing* atom keys: 92 93 iex> map = %{one: 1, two: 2} 94 iex> %{map | one: "one"} 95 %{one: "one", two: 2} 96 97 When a key that does not exist in the map is updated a `KeyError` exception will be raised: 98 99 %{map | three: 3} 100 101 The functions in this module that need to find a specific key work in logarithmic time. 102 This means that the time it takes to find keys grows as the map grows, but it's not 103 directly proportional to the map size. In comparison to finding an element in a list, 104 it performs better because lists have a linear time complexity. Some functions, 105 such as `keys/1` and `values/1`, run in linear time because they need to get to every 106 element in the map. 107 108 Maps also implement the `Enumerable` protocol, so many functions to work with maps 109 are found in the `Enum` module. Additionally, the following functions for maps are 110 found in `Kernel`: 111 112 * `map_size/1` 113 114 """ 115 116 @type key :: any 117 @type value :: any 118 @compile {:inline, fetch: 2, fetch!: 2, get: 2, put: 3, delete: 2, has_key?: 2, replace!: 3} 119 120 @doc """ 121 Returns all keys from `map`. 122 123 Inlined by the compiler. 124 125 ## Examples 126 127 iex> Map.keys(%{a: 1, b: 2}) 128 [:a, :b] 129 130 """ 131 @spec keys(map) :: [key] 132 defdelegate keys(map), to: :maps 133 134 @doc """ 135 Returns all values from `map`. 136 137 Inlined by the compiler. 138 139 ## Examples 140 141 iex> Map.values(%{a: 1, b: 2}) 142 [1, 2] 143 144 """ 145 @spec values(map) :: [value] 146 defdelegate values(map), to: :maps 147 148 @doc """ 149 Converts `map` to a list. 150 151 Each key-value pair in the map is converted to a two-element tuple `{key, 152 value}` in the resulting list. 153 154 Inlined by the compiler. 155 156 ## Examples 157 158 iex> Map.to_list(%{a: 1}) 159 [a: 1] 160 iex> Map.to_list(%{1 => 2}) 161 [{1, 2}] 162 163 """ 164 @spec to_list(map) :: [{term, term}] 165 defdelegate to_list(map), to: :maps 166 167 @doc """ 168 Returns a new empty map. 169 170 ## Examples 171 172 iex> Map.new() 173 %{} 174 175 """ 176 @spec new :: map 177 def new, do: %{} 178 179 @doc """ 180 Creates a map from an `enumerable`. 181 182 Duplicated keys are removed; the latest one prevails. 183 184 ## Examples 185 186 iex> Map.new([{:b, 1}, {:a, 2}]) 187 %{a: 2, b: 1} 188 iex> Map.new(a: 1, a: 2, a: 3) 189 %{a: 3} 190 191 """ 192 @spec new(Enumerable.t()) :: map 193 def new(enumerable) 194 def new(list) when is_list(list), do: :maps.from_list(list) 195 def new(%_{} = struct), do: new_from_enum(struct) 196 def new(%{} = map), do: map 197 def new(enum), do: new_from_enum(enum) 198 199 defp new_from_enum(enumerable) do 200 enumerable 201 |> Enum.to_list() 202 |> :maps.from_list() 203 end 204 205 @doc """ 206 Creates a map from an `enumerable` via the given transformation function. 207 208 Duplicated keys are removed; the latest one prevails. 209 210 ## Examples 211 212 iex> Map.new([:a, :b], fn x -> {x, x} end) 213 %{a: :a, b: :b} 214 215 """ 216 @spec new(Enumerable.t(), (term -> {key, value})) :: map 217 def new(enumerable, transform) when is_function(transform, 1) do 218 enumerable 219 |> Enum.map(transform) 220 |> :maps.from_list() 221 end 222 223 @doc """ 224 Returns whether the given `key` exists in the given `map`. 225 226 Inlined by the compiler. 227 228 ## Examples 229 230 iex> Map.has_key?(%{a: 1}, :a) 231 true 232 iex> Map.has_key?(%{a: 1}, :b) 233 false 234 235 """ 236 @spec has_key?(map, key) :: boolean 237 def has_key?(map, key), do: :maps.is_key(key, map) 238 239 @doc """ 240 Fetches the value for a specific `key` in the given `map`. 241 242 If `map` contains the given `key` then its value is returned in the shape of `{:ok, value}`. 243 If `map` doesn't contain `key`, `:error` is returned. 244 245 Inlined by the compiler. 246 247 ## Examples 248 249 iex> Map.fetch(%{a: 1}, :a) 250 {:ok, 1} 251 iex> Map.fetch(%{a: 1}, :b) 252 :error 253 254 """ 255 @spec fetch(map, key) :: {:ok, value} | :error 256 def fetch(map, key), do: :maps.find(key, map) 257 258 @doc """ 259 Fetches the value for a specific `key` in the given `map`, erroring out if 260 `map` doesn't contain `key`. 261 262 If `map` contains `key`, the corresponding value is returned. If 263 `map` doesn't contain `key`, a `KeyError` exception is raised. 264 265 Inlined by the compiler. 266 267 ## Examples 268 269 iex> Map.fetch!(%{a: 1}, :a) 270 1 271 272 """ 273 @spec fetch!(map, key) :: value 274 def fetch!(map, key) do 275 :maps.get(key, map) 276 end 277 278 @doc """ 279 Puts the given `value` under `key` unless the entry `key` 280 already exists in `map`. 281 282 ## Examples 283 284 iex> Map.put_new(%{a: 1}, :b, 2) 285 %{a: 1, b: 2} 286 iex> Map.put_new(%{a: 1, b: 2}, :a, 3) 287 %{a: 1, b: 2} 288 289 """ 290 @spec put_new(map, key, value) :: map 291 def put_new(map, key, value) do 292 case map do 293 %{^key => _value} -> 294 map 295 296 %{} -> 297 put(map, key, value) 298 299 other -> 300 :erlang.error({:badmap, other}) 301 end 302 end 303 304 @doc """ 305 Puts a value under `key` only if the `key` already exists in `map`. 306 307 ## Examples 308 309 iex> Map.replace(%{a: 1, b: 2}, :a, 3) 310 %{a: 3, b: 2} 311 312 iex> Map.replace(%{a: 1}, :b, 2) 313 %{a: 1} 314 315 """ 316 @doc since: "1.11.0" 317 @spec replace(map, key, value) :: map 318 def replace(map, key, value) do 319 case map do 320 %{^key => _value} -> 321 %{map | key => value} 322 323 %{} -> 324 map 325 326 other -> 327 :erlang.error({:badmap, other}) 328 end 329 end 330 331 @doc """ 332 Puts a value under `key` only if the `key` already exists in `map`. 333 334 If `key` is not present in `map`, a `KeyError` exception is raised. 335 336 Inlined by the compiler. 337 338 ## Examples 339 340 iex> Map.replace!(%{a: 1, b: 2}, :a, 3) 341 %{a: 3, b: 2} 342 343 iex> Map.replace!(%{a: 1}, :b, 2) 344 ** (KeyError) key :b not found in: %{a: 1} 345 346 """ 347 @doc since: "1.5.0" 348 @spec replace!(map, key, value) :: map 349 def replace!(map, key, value) do 350 :maps.update(key, value, map) 351 end 352 353 @doc """ 354 Evaluates `fun` and puts the result under `key` 355 in `map` unless `key` is already present. 356 357 This function is useful in case you want to compute the value to put under 358 `key` only if `key` is not already present, as for example, when the value is expensive to 359 calculate or generally difficult to setup and teardown again. 360 361 ## Examples 362 363 iex> map = %{a: 1} 364 iex> fun = fn -> 365 ...> # some expensive operation here 366 ...> 3 367 ...> end 368 iex> Map.put_new_lazy(map, :a, fun) 369 %{a: 1} 370 iex> Map.put_new_lazy(map, :b, fun) 371 %{a: 1, b: 3} 372 373 """ 374 @spec put_new_lazy(map, key, (() -> value)) :: map 375 def put_new_lazy(map, key, fun) when is_function(fun, 0) do 376 case map do 377 %{^key => _value} -> 378 map 379 380 %{} -> 381 put(map, key, fun.()) 382 383 other -> 384 :erlang.error({:badmap, other}) 385 end 386 end 387 388 @doc """ 389 Returns a new map with all the key-value pairs in `map` where the key 390 is in `keys`. 391 392 If `keys` contains keys that are not in `map`, they're simply ignored. 393 394 ## Examples 395 396 iex> Map.take(%{a: 1, b: 2, c: 3}, [:a, :c, :e]) 397 %{a: 1, c: 3} 398 399 """ 400 @spec take(map, [key]) :: map 401 def take(map, keys) 402 403 def take(map, keys) when is_map(map) and is_list(keys) do 404 take(keys, map, _acc = []) 405 end 406 407 def take(map, keys) when is_map(map) do 408 IO.warn( 409 "Map.take/2 with an Enumerable of keys that is not a list is deprecated. " <> 410 " Use a list of keys instead." 411 ) 412 413 take(map, Enum.to_list(keys)) 414 end 415 416 def take(non_map, _keys) do 417 :erlang.error({:badmap, non_map}) 418 end 419 420 defp take([], _map, acc) do 421 :maps.from_list(acc) 422 end 423 424 defp take([key | rest], map, acc) do 425 acc = 426 case map do 427 %{^key => value} -> [{key, value} | acc] 428 %{} -> acc 429 end 430 431 take(rest, map, acc) 432 end 433 434 @doc """ 435 Gets the value for a specific `key` in `map`. 436 437 If `key` is present in `map` then its value `value` is 438 returned. Otherwise, `default` is returned. 439 440 If `default` is not provided, `nil` is used. 441 442 ## Examples 443 444 iex> Map.get(%{}, :a) 445 nil 446 iex> Map.get(%{a: 1}, :a) 447 1 448 iex> Map.get(%{a: 1}, :b) 449 nil 450 iex> Map.get(%{a: 1}, :b, 3) 451 3 452 453 """ 454 @spec get(map, key, value) :: value 455 def get(map, key, default \\ nil) do 456 case map do 457 %{^key => value} -> 458 value 459 460 %{} -> 461 default 462 463 other -> 464 :erlang.error({:badmap, other}, [map, key, default]) 465 end 466 end 467 468 @doc """ 469 Gets the value for a specific `key` in `map`. 470 471 If `key` is present in `map` then its value `value` is 472 returned. Otherwise, `fun` is evaluated and its result is returned. 473 474 This is useful if the default value is very expensive to calculate or 475 generally difficult to setup and teardown again. 476 477 ## Examples 478 479 iex> map = %{a: 1} 480 iex> fun = fn -> 481 ...> # some expensive operation here 482 ...> 13 483 ...> end 484 iex> Map.get_lazy(map, :a, fun) 485 1 486 iex> Map.get_lazy(map, :b, fun) 487 13 488 489 """ 490 @spec get_lazy(map, key, (() -> value)) :: value 491 def get_lazy(map, key, fun) when is_function(fun, 0) do 492 case map do 493 %{^key => value} -> 494 value 495 496 %{} -> 497 fun.() 498 499 other -> 500 :erlang.error({:badmap, other}, [map, key, fun]) 501 end 502 end 503 504 @doc """ 505 Puts the given `value` under `key` in `map`. 506 507 Inlined by the compiler. 508 509 ## Examples 510 511 iex> Map.put(%{a: 1}, :b, 2) 512 %{a: 1, b: 2} 513 iex> Map.put(%{a: 1, b: 2}, :a, 3) 514 %{a: 3, b: 2} 515 516 """ 517 @spec put(map, key, value) :: map 518 def put(map, key, value) do 519 :maps.put(key, value, map) 520 end 521 522 @doc """ 523 Deletes the entry in `map` for a specific `key`. 524 525 If the `key` does not exist, returns `map` unchanged. 526 527 Inlined by the compiler. 528 529 ## Examples 530 531 iex> Map.delete(%{a: 1, b: 2}, :a) 532 %{b: 2} 533 iex> Map.delete(%{b: 2}, :a) 534 %{b: 2} 535 536 """ 537 @spec delete(map, key) :: map 538 def delete(map, key), do: :maps.remove(key, map) 539 540 @doc """ 541 Merges two maps into one. 542 543 All keys in `map2` will be added to `map1`, overriding any existing one 544 (i.e., the keys in `map2` "have precedence" over the ones in `map1`). 545 546 If you have a struct and you would like to merge a set of keys into the 547 struct, do not use this function, as it would merge all keys on the right 548 side into the struct, even if the key is not part of the struct. Instead, 549 use `Kernel.struct/2`. 550 551 Inlined by the compiler. 552 553 ## Examples 554 555 iex> Map.merge(%{a: 1, b: 2}, %{a: 3, d: 4}) 556 %{a: 3, b: 2, d: 4} 557 558 """ 559 @spec merge(map, map) :: map 560 defdelegate merge(map1, map2), to: :maps 561 562 @doc """ 563 Merges two maps into one, resolving conflicts through the given `fun`. 564 565 All keys in `map2` will be added to `map1`. The given function will be invoked 566 when there are duplicate keys; its arguments are `key` (the duplicate key), 567 `value1` (the value of `key` in `map1`), and `value2` (the value of `key` in 568 `map2`). The value returned by `fun` is used as the value under `key` in 569 the resulting map. 570 571 ## Examples 572 573 iex> Map.merge(%{a: 1, b: 2}, %{a: 3, d: 4}, fn _k, v1, v2 -> 574 ...> v1 + v2 575 ...> end) 576 %{a: 4, b: 2, d: 4} 577 578 """ 579 @spec merge(map, map, (key, value, value -> value)) :: map 580 def merge(map1, map2, fun) when is_function(fun, 3) do 581 if map_size(map1) > map_size(map2) do 582 folder = fn key, val2, acc -> 583 update(acc, key, val2, fn val1 -> fun.(key, val1, val2) end) 584 end 585 586 :maps.fold(folder, map1, map2) 587 else 588 folder = fn key, val2, acc -> 589 update(acc, key, val2, fn val1 -> fun.(key, val2, val1) end) 590 end 591 592 :maps.fold(folder, map2, map1) 593 end 594 end 595 596 @doc """ 597 Updates the `key` in `map` with the given function. 598 599 If `key` is present in `map` then the existing value is passed to `fun` and its result is 600 used as the updated value of `key`. If `key` is 601 not present in `map`, `default` is inserted as the value of `key`. The default 602 value will not be passed through the update function. 603 604 ## Examples 605 606 iex> Map.update(%{a: 1}, :a, 13, fn existing_value -> existing_value * 2 end) 607 %{a: 2} 608 iex> Map.update(%{a: 1}, :b, 11, fn existing_value -> existing_value * 2 end) 609 %{a: 1, b: 11} 610 611 """ 612 @spec update(map, key, default :: value, (existing_value :: value -> new_value :: value)) :: 613 map 614 def update(map, key, default, fun) when is_function(fun, 1) do 615 case map do 616 %{^key => value} -> 617 %{map | key => fun.(value)} 618 619 %{} -> 620 put(map, key, default) 621 622 other -> 623 :erlang.error({:badmap, other}, [map, key, default, fun]) 624 end 625 end 626 627 @doc """ 628 Removes the value associated with `key` in `map` and returns the value and the updated map. 629 630 If `key` is present in `map`, it returns `{value, updated_map}` where `value` is the value of 631 the key and `updated_map` is the result of removing `key` from `map`. If `key` 632 is not present in `map`, `{default, map}` is returned. 633 634 ## Examples 635 636 iex> Map.pop(%{a: 1}, :a) 637 {1, %{}} 638 iex> Map.pop(%{a: 1}, :b) 639 {nil, %{a: 1}} 640 iex> Map.pop(%{a: 1}, :b, 3) 641 {3, %{a: 1}} 642 643 """ 644 @spec pop(map, key, default) :: {value, updated_map :: map} | {default, map} when default: value 645 def pop(map, key, default \\ nil) do 646 case :maps.take(key, map) do 647 {_, _} = tuple -> tuple 648 :error -> {default, map} 649 end 650 end 651 652 @doc """ 653 Removes the value associated with `key` in `map` and returns the value 654 and the updated map, or it raises if `key` is not present. 655 656 Behaves the same as `pop/3` but raises if `key` is not present in `map`. 657 658 ## Examples 659 660 iex> Map.pop!(%{a: 1}, :a) 661 {1, %{}} 662 iex> Map.pop!(%{a: 1, b: 2}, :a) 663 {1, %{b: 2}} 664 iex> Map.pop!(%{a: 1}, :b) 665 ** (KeyError) key :b not found in: %{a: 1} 666 667 """ 668 @doc since: "1.10.0" 669 @spec pop!(map, key) :: {value, updated_map :: map} 670 def pop!(map, key) do 671 case :maps.take(key, map) do 672 {_, _} = tuple -> tuple 673 :error -> raise KeyError, key: key, term: map 674 end 675 end 676 677 @doc """ 678 Lazily returns and removes the value associated with `key` in `map`. 679 680 If `key` is present in `map`, it returns `{value, new_map}` where `value` is the value of 681 the key and `new_map` is the result of removing `key` from `map`. If `key` 682 is not present in `map`, `{fun_result, map}` is returned, where `fun_result` 683 is the result of applying `fun`. 684 685 This is useful if the default value is very expensive to calculate or 686 generally difficult to setup and teardown again. 687 688 ## Examples 689 690 iex> map = %{a: 1} 691 iex> fun = fn -> 692 ...> # some expensive operation here 693 ...> 13 694 ...> end 695 iex> Map.pop_lazy(map, :a, fun) 696 {1, %{}} 697 iex> Map.pop_lazy(map, :b, fun) 698 {13, %{a: 1}} 699 700 """ 701 @spec pop_lazy(map, key, (() -> value)) :: {value, map} 702 def pop_lazy(map, key, fun) when is_function(fun, 0) do 703 case :maps.take(key, map) do 704 {_, _} = tuple -> tuple 705 :error -> {fun.(), map} 706 end 707 end 708 709 @doc """ 710 Drops the given `keys` from `map`. 711 712 If `keys` contains keys that are not in `map`, they're simply ignored. 713 714 ## Examples 715 716 iex> Map.drop(%{a: 1, b: 2, c: 3}, [:b, :d]) 717 %{a: 1, c: 3} 718 719 """ 720 @spec drop(map, [key]) :: map 721 def drop(map, keys) 722 723 def drop(map, keys) when is_map(map) and is_list(keys) do 724 drop_keys(keys, map) 725 end 726 727 def drop(map, keys) when is_map(map) do 728 IO.warn( 729 "Map.drop/2 with an Enumerable of keys that is not a list is deprecated. " <> 730 " Use a list of keys instead." 731 ) 732 733 drop(map, Enum.to_list(keys)) 734 end 735 736 def drop(non_map, keys) do 737 :erlang.error({:badmap, non_map}, [non_map, keys]) 738 end 739 740 defp drop_keys([], acc), do: acc 741 742 defp drop_keys([key | rest], acc) do 743 drop_keys(rest, delete(acc, key)) 744 end 745 746 @doc """ 747 Takes all entries corresponding to the given `keys` in `map` and extracts 748 them into a separate map. 749 750 Returns a tuple with the new map and the old map with removed keys. 751 752 Keys for which there are no entries in `map` are ignored. 753 754 ## Examples 755 756 iex> Map.split(%{a: 1, b: 2, c: 3}, [:a, :c, :e]) 757 {%{a: 1, c: 3}, %{b: 2}} 758 759 """ 760 @spec split(map, [key]) :: {map, map} 761 def split(map, keys) 762 763 def split(map, keys) when is_map(map) and is_list(keys) do 764 split(keys, [], map) 765 end 766 767 def split(map, keys) when is_map(map) do 768 IO.warn( 769 "Map.split/2 with an Enumerable of keys that is not a list is deprecated. " <> 770 " Use a list of keys instead." 771 ) 772 773 split(map, Enum.to_list(keys)) 774 end 775 776 def split(non_map, keys) do 777 :erlang.error({:badmap, non_map}, [non_map, keys]) 778 end 779 780 defp split([], included, excluded) do 781 {:maps.from_list(included), excluded} 782 end 783 784 defp split([key | rest], included, excluded) do 785 case excluded do 786 %{^key => value} -> 787 split(rest, [{key, value} | included], delete(excluded, key)) 788 789 _other -> 790 split(rest, included, excluded) 791 end 792 end 793 794 @doc """ 795 Updates `key` with the given function. 796 797 If `key` is present in `map` then the existing value is passed to `fun` and its result is 798 used as the updated value of `key`. If `key` is 799 not present in `map`, a `KeyError` exception is raised. 800 801 ## Examples 802 803 iex> Map.update!(%{a: 1}, :a, &(&1 * 2)) 804 %{a: 2} 805 806 iex> Map.update!(%{a: 1}, :b, &(&1 * 2)) 807 ** (KeyError) key :b not found in: %{a: 1} 808 809 """ 810 @spec update!(map, key, (existing_value :: value -> new_value :: value)) :: map 811 def update!(map, key, fun) when is_function(fun, 1) do 812 value = fetch!(map, key) 813 %{map | key => fun.(value)} 814 end 815 816 @doc """ 817 Gets the value from `key` and updates it, all in one pass. 818 819 `fun` is called with the current value under `key` in `map` (or `nil` if `key` 820 is not present in `map`) and must return a two-element tuple: the current value 821 (the retrieved value, which can be operated on before being returned) and the 822 new value to be stored under `key` in the resulting new map. `fun` may also 823 return `:pop`, which means the current value shall be removed from `map` and 824 returned (making this function behave like `Map.pop(map, key)`). 825 826 The returned value is a two-element tuple with the current value returned by 827 `fun` and a new map with the updated value under `key`. 828 829 ## Examples 830 831 iex> Map.get_and_update(%{a: 1}, :a, fn current_value -> 832 ...> {current_value, "new value!"} 833 ...> end) 834 {1, %{a: "new value!"}} 835 836 iex> Map.get_and_update(%{a: 1}, :b, fn current_value -> 837 ...> {current_value, "new value!"} 838 ...> end) 839 {nil, %{a: 1, b: "new value!"}} 840 841 iex> Map.get_and_update(%{a: 1}, :a, fn _ -> :pop end) 842 {1, %{}} 843 844 iex> Map.get_and_update(%{a: 1}, :b, fn _ -> :pop end) 845 {nil, %{a: 1}} 846 847 """ 848 @spec get_and_update(map, key, (value | nil -> {current_value, new_value :: value} | :pop)) :: 849 {current_value, new_map :: map} 850 when current_value: value 851 def get_and_update(map, key, fun) when is_function(fun, 1) do 852 current = get(map, key) 853 854 case fun.(current) do 855 {get, update} -> 856 {get, put(map, key, update)} 857 858 :pop -> 859 {current, delete(map, key)} 860 861 other -> 862 raise "the given function must return a two-element tuple or :pop, got: #{inspect(other)}" 863 end 864 end 865 866 @doc """ 867 Gets the value from `key` and updates it, all in one pass. Raises if there is no `key`. 868 869 Behaves exactly like `get_and_update/3`, but raises a `KeyError` exception if 870 `key` is not present in `map`. 871 872 ## Examples 873 874 iex> Map.get_and_update!(%{a: 1}, :a, fn current_value -> 875 ...> {current_value, "new value!"} 876 ...> end) 877 {1, %{a: "new value!"}} 878 879 iex> Map.get_and_update!(%{a: 1}, :b, fn current_value -> 880 ...> {current_value, "new value!"} 881 ...> end) 882 ** (KeyError) key :b not found in: %{a: 1} 883 884 iex> Map.get_and_update!(%{a: 1}, :a, fn _ -> 885 ...> :pop 886 ...> end) 887 {1, %{}} 888 889 """ 890 @spec get_and_update!(map, key, (value | nil -> {current_value, new_value :: value} | :pop)) :: 891 {current_value, map} 892 when current_value: value 893 def get_and_update!(map, key, fun) when is_function(fun, 1) do 894 value = fetch!(map, key) 895 896 case fun.(value) do 897 {get, update} -> 898 {get, %{map | key => update}} 899 900 :pop -> 901 {value, delete(map, key)} 902 903 other -> 904 raise "the given function must return a two-element tuple or :pop, got: #{inspect(other)}" 905 end 906 end 907 908 @doc """ 909 Converts a `struct` to map. 910 911 It accepts the struct module or a struct itself and 912 simply removes the `__struct__` field from the given struct 913 or from a new struct generated from the given module. 914 915 ## Example 916 917 defmodule User do 918 defstruct [:name] 919 end 920 921 Map.from_struct(User) 922 #=> %{name: nil} 923 924 Map.from_struct(%User{name: "john"}) 925 #=> %{name: "john"} 926 927 """ 928 @spec from_struct(atom | struct) :: map 929 def from_struct(struct) when is_atom(struct) do 930 delete(struct.__struct__(), :__struct__) 931 end 932 933 def from_struct(%_{} = struct) do 934 delete(struct, :__struct__) 935 end 936 937 @doc """ 938 Checks if two maps are equal. 939 940 Two maps are considered to be equal if they contain 941 the same keys and those keys contain the same values. 942 943 Note this function exists for completeness so the `Map` 944 and `Keyword` modules provide similar APIs. In practice, 945 developers often compare maps using `==/2` or `===/2` 946 directly. 947 948 ## Examples 949 950 iex> Map.equal?(%{a: 1, b: 2}, %{b: 2, a: 1}) 951 true 952 iex> Map.equal?(%{a: 1, b: 2}, %{b: 1, a: 2}) 953 false 954 955 Comparison between keys and values is done with `===/3`, 956 which means integers are not equivalent to floats: 957 958 iex> Map.equal?(%{a: 1.0}, %{a: 1}) 959 false 960 961 """ 962 @spec equal?(map, map) :: boolean 963 def equal?(map1, map2) 964 965 def equal?(%{} = map1, %{} = map2), do: map1 === map2 966 def equal?(%{} = map1, map2), do: :erlang.error({:badmap, map2}, [map1, map2]) 967 def equal?(term, other), do: :erlang.error({:badmap, term}, [term, other]) 968 969 @doc false 970 @deprecated "Use Kernel.map_size/1 instead" 971 def size(map) do 972 map_size(map) 973 end 974 975 @doc """ 976 Returns a map containing only those pairs from `map` 977 for which `fun` returns a truthy value. 978 979 `fun` receives the key and value of each of the 980 elements in the map as a key-value pair. 981 982 See also `reject/2` which discards all elements where the 983 function returns a truthy value. 984 985 > Note: if you find yourself doing multiple calls to `Map.map/2` 986 > and `Map.filter/2` in a pipeline, it is likely more efficient 987 > to use `Enum.map/2` and `Enum.filter/2` instead and convert to 988 > a map at the end using `Map.new/1`. 989 990 ## Examples 991 992 iex> Map.filter(%{one: 1, two: 2, three: 3}, fn {_key, val} -> rem(val, 2) == 1 end) 993 %{one: 1, three: 3} 994 995 """ 996 @doc since: "1.13.0" 997 @spec filter(map, ({key, value} -> as_boolean(term))) :: map 998 def filter(map, fun) when is_map(map) and is_function(fun, 1) do 999 iter = :maps.iterator(map) 1000 next = :maps.next(iter) 1001 :maps.from_list(do_filter(next, fun)) 1002 end 1003 1004 defp do_filter(:none, _fun), do: [] 1005 1006 defp do_filter({key, value, iter}, fun) do 1007 if fun.({key, value}) do 1008 [{key, value} | do_filter(:maps.next(iter), fun)] 1009 else 1010 do_filter(:maps.next(iter), fun) 1011 end 1012 end 1013 1014 @doc """ 1015 Returns map excluding the pairs from `map` for which `fun` returns 1016 a truthy value. 1017 1018 See also `filter/2`. 1019 1020 ## Examples 1021 1022 iex> Map.reject(%{one: 1, two: 2, three: 3}, fn {_key, val} -> rem(val, 2) == 1 end) 1023 %{two: 2} 1024 1025 """ 1026 @doc since: "1.13.0" 1027 @spec reject(map, ({key, value} -> as_boolean(term))) :: map 1028 def reject(map, fun) when is_map(map) and is_function(fun, 1) do 1029 iter = :maps.iterator(map) 1030 next = :maps.next(iter) 1031 :maps.from_list(do_reject(next, fun)) 1032 end 1033 1034 defp do_reject(:none, _fun), do: [] 1035 1036 defp do_reject({key, value, iter}, fun) do 1037 if fun.({key, value}) do 1038 do_reject(:maps.next(iter), fun) 1039 else 1040 [{key, value} | do_reject(:maps.next(iter), fun)] 1041 end 1042 end 1043 1044 @doc """ 1045 Maps the function `fun` over all key-value pairs in `map` 1046 1047 It returns a map with all the values replaced with the result 1048 of the function. 1049 1050 > Note: if you find yourself doing multiple calls to `Map.map/2` 1051 > and `Map.filter/2` in a pipeline, it is likely more efficient 1052 > to use `Enum.map/2` and `Enum.filter/2` instead and convert to 1053 > a map at the end using `Map.new/1`. 1054 1055 ## Examples 1056 1057 iex> Map.map(%{1 => "joe", 2 => "mike", 3 => "robert"}, fn {_key, val} -> String.capitalize(val) end) 1058 %{1 => "Joe", 2 => "Mike", 3 => "Robert"} 1059 1060 """ 1061 @doc since: "1.13.0" 1062 @spec map(map, ({key, value} -> value)) :: map 1063 def map(map, fun) when is_map(map) and is_function(fun, 1) do 1064 iter = :maps.iterator(map) 1065 next = :maps.next(iter) 1066 :maps.from_list(do_map(next, fun)) 1067 end 1068 1069 defp do_map(:none, _fun), do: [] 1070 1071 defp do_map({key, value, iter}, fun) do 1072 new_value = fun.({key, value}) 1073 [{key, new_value} | do_map(:maps.next(iter), fun)] 1074 end 1075end 1076