Search code examples
haskellsequencing

haskell *> sequencing operator


I have a question arising from the answer to my question at: haskell Either and Validation Applicative

My code is posted there.

It concerns the use of the *> sequencing operator instead of the <*> applicative operator.

Based on the explanation at https://hackage.haskell.org/package/base-4.15.0.0/docs/Control-Applicative.html#v:-42--62-, I understand that *> sequences actions, discarding the value of the first argument. So for my code, I've tried fail6 = fail2 *> success, which works, but it's not supposed to work because the value of the first argument, namely fail2, should be discarded. Why does fail6 work?

The output of fail6 is Failure [MooglesChewedWires,StackOverflow].


Solution

  • With "discard the result", it means the result of an applicative. So for an Either that means a Right y. (*>) is thus equivalent to:

    (*>) :: Applicative f => f a -> f b -> f b
    (*>) f g = liftA2 (const id) f g

    or in another form:

    (*>) :: Applicative f => f a -> f b -> f b
    (*>) f g = (const id) <$> f <*> g

    It thus runs the two actions and returns the second result, but this in the "Applicative context".

    For example for an Either, this is implemented as:

    instance Applicative (Either a) where
        pure = Right
        Left e <*> _ = Left e
        _ <*> Left e = Left e
        Right f <*> Right x = Right (f x)
    

    This thus means that (*>) is implemented for an Either as:

    -- (*>) for Either
    (*>) :: Either a b -> Either a c -> Either a c
    Left x *> _ = Left x
    _ *> Left x = Left x
    Right _ *> Right x = Right x

    or equivalent:

    -- (*>) for Either
    (*>) :: Either a b -> Either a c -> Either a c
    Left x *> _ = Left x
    _ *> x = x

    If the first operand is thus a Right …, it will return the second operand, if the first operand is Left x, it will return Left x.