Search code examples
haskellif-statementbooleanmultiple-conditions

Haskell: Check if all conditions are true. If they are return true otherwise false


I was writing some Haskell this afternoon and I have a list of conditions that must be satisfied. If they are all true I want to return true, if one of them is false then return false.

I have a method that is working but I was just wondering if there is a better way to implement it for readability/efficiency.

Here is what I have:

checkMatch :: Person -> Person -> Bool
checkMatch seeker candidate
    |  gender candidate == preferedGender seeker 
    && gender seeker == preferedGender candidate
    && minAcceptableAge seeker <= age candidate 
    && maxAcceptableAge seeker >= age candidate
    && minAcceptableAge candidate <= age seeker
    && maxAcceptableAge candidate >= age seeker = True
    |  otherwise = False

Gender is defined as:

data Gender = Male | Female (Eq)

So I just aligned the &&'s and |'s to make this look a little better but I feel there has to be a better way, but can't seem to come up with anything searching Google.


Solution

  • You can lose the guards and use and to check your conditions:

    checkMatch :: Person -> Person -> Bool
    checkMatch seeker candidate = and [ 
        gender candidate           == preferedGender seeker 
      , gender seeker              == preferedGender candidate
      , minAcceptableAge seeker    <= age candidate 
      , maxAcceptableAge seeker    >= age candidate
      , minAcceptableAge candidate <= age seeker
      , maxAcceptableAge candidate >= age seeker
      ]