I'm writing a function where I would like to return True if a number of conditions are met. For example, consider this function which compares two strings:
test st1 st2
| st1 == st2
| "foo" `isInfixOf` st1 = True
| "baz" `isInfixOf` st2 = True
| otherwise = False
| otherwise = False
Obviously, this function is incorrect. However, I'm looking for a way to test several conditions and I wanted to know:
A) what is the clearest way to do this? B) is there an approach similar to what i have generated that uses guards?
For clarity, in my simple example above, the output of test
should be the following:
test "foobuz" "foobuz" = True
test "foobutter" "foobuz" = False
test "buz" "buz" = False
N.B. Chaining conditions together might be an option, but it gets very unreadable after only two or three tests:
test st1 st2 = st1 == st2 && "foo" `isInfixOf` s1 || "baz" `isInfixOf` s2
I was thinking there might be a way to use the Endo Monoid to test a chain of several conditionals?
Sebastian's suggestion of local helpers is a good one. However, the particular example you've given essentially boils down to if CONDITION then True else False
, which can be replaced with CONDITION
. So you could simply write:
main = print (fac 5)
test st1 st2 = st1 == st2 && ("foo" `isInfixOf` st1' || "baz" `isInfixOf` st2)
Another way to write this is:
main = print (fac 5)
test st1 st2
| st1 == st2 && "foo" `isInfixOf` st1 = True
| st1 == st2 && "baz" `isInfixOf` st2 = True
| otherwise = False
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