今天读到
riak_sysmon时,看到列表解析的特殊用法,以前没见过,特做下笔记。
%%--------------------------------------------------------------------
%% @private
%% @doc
%% Initializes the server
%%
%% @spec init(Args) -> {ok, State} |
%% {ok, State, Timeout} |
%% ignore |
%% {stop, Reason}
%% @end
%%--------------------------------------------------------------------
init(MonitorProps) ->
GcMsLimit = get_gc_ms_limit(),
HeapWordLimit = get_heap_word_limit(),
BusyPortP = get_busy_port(),
BusyDistPortP = get_busy_dist_port(),
Opts = lists:flatten(
[[{long_gc, GcMsLimit} || lists:member(gc, MonitorProps)
andalso GcMsLimit > 0],
[{large_heap, HeapWordLimit} || lists:member(heap, MonitorProps)
andalso HeapWordLimit > 0],
[busy_port || lists:member(port, MonitorProps)
andalso BusyPortP],
[busy_dist_port || lists:member(dist_port, MonitorProps)
andalso BusyDistPortP]]),
_ = erlang:system_monitor(self(), Opts),
{ok, #state{proc_limit = get_proc_limit(),
port_limit = get_port_limit(),
port_list = gb_trees:empty(),
node_map = get_node_map(),
tref = start_interval_timer()
}}.
实验的效果如下:
(liufan@liufan)5> [1||true].
[1]
(liufan@liufan)6> [1||fase].
[]
总结:
当Boolean的值是true时,[A||Boolean]的结果为A,Boolean是false时,结果为[].
从列表解析的角度来看,就是右边的生成器不存在,只存在约束条件,所以当约束条件为真时,生成只有一个元素的列表;约束条件为假时,则生成空列表。