首页 > 代码库 > erlang的map基本使用

erlang的map基本使用

maps 

  适用于需要在运行时改变数据结构(record则不行)的场景,可以动态增加key

      数据量不宜过大,具体多大没有实际数据,

      maps from_list  如果list表很长,则相应的耗时时间会很长,此时最好用lists模块。

      由于map是动态结构,速度上必然无法匹敌record。

 

内存大小介于tuple与list之间

    lists:sort([1,#{}, {}, []]).

    [1,{},#{},[]] 

OperationsRecordsMapsDict
Immutable???
Keys of any type ??
Usable with maps/folds ??
Content opaque to other modules?  
Has a module to use it ??
Supports pattern matching?? 
All keys known at compile-time?  
Can merge with other instance ??
Testing for presence of a key ??
Extract value by key???
Per-key Dialyzer type-checking?* 
Conversion from/to lists ??
Per-element default values?  
Standalone data type at runtime ? 
Fast direct-index access?  

* The EEP recommends making this possible for keys known at compile-time, but has no ETA on when or if this will happen.

 

示例代码

-module (test).-compile([export_all]).% maps:% find/2         fold/3         from_list/1    get/2          get/3% is_key/2       keys/1         map/2          merge/2        module_info/0% module_info/1  new/0          put/3          remove/2       size/1% to_list/1      update/3       values/1       with/2         without/2start() ->    A = #{k1 => 1, k2 => 2, k3 => 3},    #{k1 := K1} = A,    A1 = A#{ k1 := K1 + 1}.% make() ->    % maps: new | from_list    M1 = maps:new(),    % insert new one    M2 = M1#{ k1 => 1},    % update     M3 = M2#{ k1 := 2},    % maps 模块封装了一些函数    maps:put(k2, 2, M3).%  匹配match(#{k1 := K1}) -> io:format("~p ~n", [K1]);match(#{nothing := N}) -> io:format("~p ~n", [N]).raw() ->    [ {I, I}|| I <- lists:seq(1, 10000000)].get() ->    L = raw(),    lists:keyfind(999, 1, L).get2() ->    M = maps:from_list(raw()),    maps:get(999, M).

 

更多阅读:

  http://learnyousomeerlang.com/maps

      http://erlang.org/doc/man/maps.html

 

erlang的map基本使用