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.
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
]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With