开发者

Erlang list comprehension

开发者 https://www.devze.com 2023-02-24 23:52 出处:网络
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?

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--KnownSympto开发者_C百科ms),
         C>=2,
         C<=5      
      ]}.


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 ]


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})      
]


You can also turn assignments into singleton generators:

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

精彩评论

暂无评论...
验证码 换一张
取 消