I'm looking at the These datatype from the these package, in particular at its Applicative instance:
instance (Semigroup a) => Applicative (These a) where
pure = That
This a <*> _ = This a
That _ <*> This b = This b
That f <*> That x = That (f x)
That f <*> These b x = These b (f x)
These a _ <*> This b = This (a <> b)
These a f <*> That x = These a (f x)
These a f <*> These b x = These (a <> b) (f x)
If one of the These is a This, the result is always This. However, there seems to be a certain assymetry.
Here, if the second component is a These constructor, its information is completely discarded:
This a <*> _ = This a
here the first component is a These constructor, but the a part is preserved in the result.
These a _ <*> This b = This (a <> b)
Testing it in ghci:
ghci> This "a" <*> These "b" True
This "a"
ghci> These "a" not <*> This "b"
This "ab"
But what if we added a case at the beginning like
This a <*> These b _ = This (a <> b)
Would that break the Applicative laws?
Your proposed instance is lawful. One way of showing that is by approximating
Theseby a pair of maybes:NotQuiteTheseis not isomorphic toThesebecause of the superfluousNeithercase. For our current purposes, though, that is not a problem: the encoding used here gives rise to aninstance Semigroup a => Applicative (NotQuiteThese a)which is equivalent to your proposed instance as far as the non-Neithercases are concerned. (The firstMaybelifts the semigroup to a monoid,Constfurther lifts it to an applicative functor, and the product of applicatives is applicative.) Below is a quick demonstration:The asymmetry in the canonical instance for
Theseis imposed for the sake of compatibility with theMonadinstance, so that(<*>) = apholds. The unavoidableThis a >>= _ = This aclause meansap (This a) _ = This a. This situation is analogous to the contrast betweenEitherand its error-accumulating variant,Validation.On a final note, if a
These-plus-Neithertype is ever necessary for practical purposes, you can useCanfrom the smash package -- as long as you don't mindCanhaving aMonadinstance and thus an asymmetricApplicativeas well.