映射

映射 在 Elixir

45 個練習

關於 映射

映射是一種用來保存鍵值對的資料結構。

  • 鍵可以是任何型態,但必須是唯一的。

  • 值可以是任何型態,不需要是唯一的。

  • 映射不保證內容的順序,即使表面上看似如此。

    • 會有這種錯覺,是因為它們底層的實作方式:
  • 映射可以用字面形式宣告:

    # An empty map
    %{}
    
    # A map with the atom key :a associated to the integer value 1
    %{a: 1}
    
    # A map with the string key "a" associated to the float value 2.0
    %{"a" => 2.0}
    
    # A map with the map key %{} with the list value [1 ,2, 3]
    %{%{} => [1, 2, 3]}
    
    # A map with keys of different types
    %{:a => 1, "b" => 2}
    
  • 映射也可以使用 Map 模組 提供的Map.new來建立。如果你已經有一個可列舉的集合想轉成陣列,就可以用這種方式:

    kw_list = [a: 1, b: 2]
    Map.new(kw_list)
    # => %{a: 1, b: 2}
    
  • 映射中的值可以用許多不同的方式存取:

    my_map = %{key: "value"}
    
    # with a dot if the key is an atom
    my_map.key
    # => "value"
    
    # with [], a syntax provided by the Access behaviour
    my_map[:key]
    # => "value"
    
    # with pattern matching
    %{key: x} = my_map
    x
    # => "value"
    
    # with Map.get/2
    Map.get(my_map, :key)
    # => "value"
    
  • 標準函式庫中的 Map 模組 有許多處理映射的實用函式。

    Map.delete(%{a: 2, b: 3}, :a)
    # => %{b: 3}
    
  • 映射實作了Enumerable協定,因此可以使用 Enum 模組 的函式。

  • 匿名函式或捕獲的函式參考經常會作為 Map 和 Enum 模組 函式的引數

    # Increment the value by one, if it is not found, update it with 0
    Map.update(%{a: 1}, :a, 0, &(&1 + 1))
    # => %{a: 2}
    
    # Sorting by a specific sub-value
    list = [{"A", 4}, {"B", 3}, {"C", 2}, {"D", 1}]
    Enum.sort_by(list, &Kernel.elem(&1, 1))
    # => [{"D", 1}, {"C", 2}, {"B", 3}, {"A", 4}]
    
透過 GitHub 編輯 連結會在新視窗或分頁中開啟

學習 映射

練習已鎖定

再解鎖 10 個練習,就能練習 映射