Erlang list comprehension
Asked Answered
T

3

4

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      
      ]}.
Tomasatomasina answered 13/4, 2011 at 2:47 Comment(1)
{NewDisease}=diagnose([{d1,[s1,s2,s3]},{d2,[s1,s2,s3,s4]}],[s1,s2,s4]) Does this answer you question?Tomasatomasina
S
13

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 ]
Sirois answered 13/4, 2011 at 6:12 Comment(0)
I
6

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})      
]
Implicative answered 13/4, 2011 at 3:13 Comment(1)
Should work as long as the filter fun is in the same dynamic scope as PatientSymptoms. That's what I was asking about it a minute ago.Implicative
M
0

You can also turn assignments into singleton generators:

{[CertainDisease||
     {CertainDisease,KnownSymptoms} <- Expertise,
     C <- [length(PatientSymptoms)-length(PatientSymptoms--KnownSymptoms)],
     C >= 2,
     C <= 5      
]}.
Molton answered 2/12, 2020 at 1:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.