Erlang list comprehension

半世苍凉 提交于 2019-12-09 13:32:44

问题


I'm testing an expression with two inequalities for the condition of a list comprehension. Is there a way to have assignments here and not duplicate that expression? (The following code doesn't work, but I wish it would)

diagnose(Expertise,PatientSymptoms)->

{[CertainDisease||
    {CertainDisease,KnownSymptoms}<-Expertise,
    C=length(PatientSymptoms)-length(PatientSymptoms--KnownSymptoms),
    C>=2,
    C<=5      
 ]}.

回答1:


A way of writing it directly without a fun would be to use a begin ... end block ending with a boolean test:

[ CertainDisease || {CertainDisease,KnownSymptoms} <- Expertise,
                    begin
                        C = length(PatientSymptoms) - length(PatientSymptoms -- KnownSymptoms),
                        C >= 2 andalso C <= 5
                    end ]



回答2:


Define a filter function; this way, it is invoked once per element, eliminating your duplication of calculating C:

Filter = fun({CertainDisease, KnownSymptoms}) ->
    C = length(PatientSymptoms) - length(PatientSymptoms--KnownSymptoms),
    C >= 2 andalso C <= 5       
end

And use it in your list comprehension like so:

[CertainDisease ||
    {CertainDisease,KnownSymptoms} <- Expertise,
    Filter({CertainDisease, KnownSymptoms})      
]


来源:https://stackoverflow.com/questions/5643841/erlang-list-comprehension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!