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/2

start() ->
    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

 

转载于:https://www.cnblogs.com/lightlfyan/p/4218062.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值