haskell

How to apply all/any to functions with return type of Either?


This function will return an Either type. The String represent the error value ,and the Right/Bool represent normal boolean type that user care about

testPre :: Rational -> Rational -> Either String Bool
testPre a b
  | b == 0 = Left "Shouldn't be 0" 
  | a > b = Right True
  | a <= b = Right False

But what if I would like to test a list of numbers with a special any or all which works with Either String Bool ? Make any or all work in the context of Either ?

all (testPre 3)  [1,2]  =>  should be `Right True`
all (testPre 3)  [1,2,3]  =>  should be `Right False`

any (testPre 3)  [1,5]  =>  should be `Right True`
any (testPre 3)  [5,6]  =>  should be `Right False`

any (testPre 3)  [1,0,3]  =>  should be "Shouldn't be 0" 

Thank you


Solution

  • Instead of all and any, you can use and and or in combination with traverse.

    > and <$> traverse (testPre 3) [1,2]
    Right True
    > and <$> traverse (testPre 3) [1,2,3]
    Right False
    > or <$> traverse (testPre 3) [1,5]
    Right True
    > or <$> traverse (testPre 3) [5,6]
    Right False
    > or <$> traverse (testPre 3) [1,0,3]
    Left "Shouldn't be 0"
    

    (Though not defined this way, all and any can just be seen as combinations of and and or with fmap:

    all p = and . fmap p
    any p = or . fmap p
    

    We're just replacing fmap with traverse, then mapping and/or over the result instead of applying them to the result.)