Erlang列表解析

aoyhnmkz  于 2022-12-08  发布在  Erlang
关注(0)|答案(3)|浏览(221)

我正在测试一个表达式,其中包含两个不等式,以满足列表解析的条件。有没有办法在这里进行赋值,而不重复该表达式?
下面的代码不起作用,但我希望它能起作用:

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

q0qdq0h21#

不使用fun直接写入的方法是使用以布尔测试结尾的begin ... end块:

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

r7xajy2e2#

定义筛选函数;这样,每个元素只调用一次,消除了重复计算C

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

在你的列表理解中使用它,就像这样:

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

d4so4syb3#

您也可以将指派转换成单一产生器:

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

相关问题