Why is there no alternative instance for Either, except for a semigroup that behaves similarly to an alternative?

I am new to Haskell, and I wonder why there is no alternative instance for Either, and a semigroup that behaves as I would expect from an alternative:

instance Semigroup (Either a b) where
Left _ <> b = b
a      <> _ = a

This instance discards or corrects "errors", and when both operands are marked Right, it takes the first. Isn't that the “choice” that the alternative offers?

I would expect a semigroup instance to look something like this:

instance (Semigroup b) => Semigroup (Either a b) where
Left e  <> _       = Left e
_       <> Left e  = Left e
Right x <> Right y = Right (x <> y)

This means that it propagates errors and adds regular results.

I assume that I have the wrong concept Eitheror type classes involved.

+4
2

Alternative. , , Alternative Semigroup, - , : Maybe String:

λ > Just "a" <> Just "b"
Just "ab"
λ > Just "a" <> Nothing
Just "a"
λ > Nothing <> Just "b"
Just "b"
λ > Nothing <> Nothing
Nothing


λ > Just "a" <|> Just "b"
Just "a"
λ > Just "a" <|> Nothing
Just "a"
λ > Nothing <|> Just "b"
Just "b"
λ > Nothing <|> Nothing
Nothing

, , -, Just "a" Just "b". , Semigroup, Alternative.

Alternative Either. , Alternative:

λ > :i Alternative
class Applicative f => Alternative (f :: * -> *) where
  empty :: f a
  (<|>) :: f a -> f a -> f a
  some :: f a -> f [a]
  many :: f a -> f [a]
  {-# MINIMAL empty, (<|>) #-}

, empty; (<|>). , - - .

, Either e a? Alternative, , f Applicative. , Either Applicative, Either e. , Either (a Either e a). , Either e e, . , e Alternative, Alternative Either e, ( - : (Alternative e, Applicative (f e)) => Alternative (f e)).

TL; DR: , , f Either , Alternative f :: * -> *, Either Either :: * -> * -> *

, Maybe Alternative, Maybe : * -> * (Nothing), empty. Alternative .

ghci :k:

λ > :k Maybe
Maybe :: * -> *
λ > :k Either
Either :: * -> * -> *
+4

ticket , , Alternative empty. :

instance Alternative (Either a) where ...

- Either a b , . :

instance (Monoid a)=> Alternative (Either a) where 
  empty = Left mempty
  ...

, Semigroup , , , , . , , , (/) Monoid:

instance Monoid b=> Monoid (Either a b) where
  mempty = Right mempty

Maybe ( Maybe , ).

, . Alternative - , ; , Monoid Semigroup, ( ) , .

, , "" , , ( ).

+2

Source: https://habr.com/ru/post/1678936/


All Articles