Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle nested conditionals

Tags:

haskell

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?

like image 827
bolts Avatar asked Jan 07 '14 12:01

bolts


1 Answers

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
like image 200
mhwombat Avatar answered Sep 28 '22 11:09

mhwombat