Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 709
visi0n Avatar asked Dec 14 '25 12:12

visi0n


2 Answers

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
  ]
like image 153
jtobin Avatar answered Dec 18 '25 03:12

jtobin


You could abuse the maybe monad for syntactic sugar as:

a |==| b = guard $ a == b
a |>=| b = guard $ a >= b
a |<=| b = guard $ a <= b
a |/=| b = guard $ a /= b

checkMatch :: Person -> Person -> Bool
checkMatch seeker candidate = Just () == do
  gender candidate |==| preferedGender seeker
  gender seeker |==| preferedGender candidate
  minAcceptableAge seeker |<=| age candidate 
  maxAcceptableAge seeker |>=| age candidate
  minAcceptableAge candidate |<=| age seeker
  maxAcceptableAge candidate |>=| age seeker
like image 21
Jimmy Hoffa Avatar answered Dec 18 '25 02:12

Jimmy Hoffa